算法----字符串

412 阅读3分钟

我的算法之路,计划一年时间,刷题2000道

链表

数组

1 最大数

给定一组非负整数 nums,重新排列每个数的顺序(每个数不可拆分)使之组成一个最大的整数。

注意:输出结果可能非常大,所以你需要返回一个字符串而不是整数。

leetcode-cn.com/problems/la…

    public String largestNumber(int[] nums) {
        if (nums == null || nums.length == 0) {
            return "";
        }
        String[] strAtr = new String[nums.length];
        for (int i = 0; i < strAtr.length; i++) {
            strAtr[i] = String.valueOf(nums[i]);
        }

        Arrays.sort(strAtr, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return (o2 + o1).compareTo(o1 + o2);
            }
        });

        StringBuilder sb = new StringBuilder();
        for (String aStrArr : strAtr) {
            sb.append(aStrArr);
        }
        String result = sb.toString();
        if ('0' == result.charAt(0)) {
            result = "0";
        }
        return result;
    }
}

2 有多少小于当前数字的数字

给你一个数组 nums,对于其中每个元素 nums[i],请你统计数组中比它小的所有数字的数目。

换而言之,对于每个 nums[i] 你必须计算出有效的 j 的数量,其中 j 满足 j != i 且 nums[j] < nums[i] 。

以数组形式返回答案。 

示例 1:

输入:nums = [8,1,2,2,3] 输出:[4,0,1,1,3] 解释: 对于 nums[0]=8 存在四个比它小的数字:(1,2,2 和 3)。 对于 nums[1]=1 不存在比它小的数字。 对于 nums[2]=2 存在一个比它小的数字:(1)。 对于 nums[3]=2 存在一个比它小的数字:(1)。 对于 nums[4]=3 存在三个比它小的数字:(1,2 和 2)。

来源:力扣(LeetCode)

链接:leetcode-cn.com/problems/ho…

class Solution {
    public int[] smallerNumbersThanCurrent(int[] nums) {
        int n=nums.length;
		int []res=new int[n];
		for(int i=0;i<n;i++) {
			for(int j=0;j<n;j++) {
				if(i==j)continue;
				if(nums[j]<nums[i]) {
					res[i]++;
				}
			}
		}
		return res;
    }
}

3 最长不含重复字符的子字符串

请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。

 

示例 1:

输入: "abcabcbb" 输出: 3 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。

来源:力扣(LeetCode)

链接:leetcode-cn.com/problems/zu…

 public int lengthOfLongestSubstring(String s) {
        if (s.length() <= 0) {
            return 0;
        }
        int left = 0;
        int right = 0;
        int length = 0;

        HashSet<Character> hashSet = new HashSet<>();
        while (right < s.length()) {
            if (hashSet.contains(s.charAt(right))) {
                hashSet.remove(s.charAt(left));
                left++;
            } else {
                hashSet.add(s.charAt(right));
                right++;
            }
            length = hashSet.size() > length ? hashSet.size() : length;
        }
        return length;
    }

4 无重复字符的最长子串

给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。

 

示例 1:

输入: s = "abcabcbb" 输出: 3 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。 示例 2:

输入: s = "bbbbb" 输出: 1 解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。

来源:力扣(LeetCode)

链接:leetcode-cn.com/problems/lo…

 public int lengthOfLongestSubstring(String args) {
         if (args.length() <= 0) {
            return 0;
        }

        int left = 0;
        int right = 0;
        int length = 0;
        HashSet<Character> hashSet = new HashSet<>();
        while (right < args.length()) {
            if (hashSet.contains(args.charAt(right))) {
                hashSet.remove(args.charAt(left++));
            } else {
                hashSet.add(args.charAt(right++));
            }
            length = hashSet.size() > length ? hashSet.size() : length;
        }
        return length;
    }

5 最长公共前缀

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""。

示例 1:

输入:strs = ["flower","flow","flight"] 输出:"fl" 示例 2:

输入:strs = ["dog","racecar","car"] 输出:"" 解释:输入不存在公共前缀。

来源:力扣(LeetCode)

链接:leetcode-cn.com/problems/lo…

public String longestCommonPrefix(String[] strs) {
        if (strs.length == 0) {
            return "";
        }
        String s = strs[0];
        for (String str : strs) {
            while (!str.startsWith(s)) {
                s = s.substring(0, s.length() - 1);
            }
        }
        return s;
    }

6 删除字符串中的所有相邻重复项

给出由小写字母组成的字符串 S,重复项删除操作会选择两个相邻且相同的字母,并删除它们。

在 S 上反复执行重复项删除操作,直到无法继续删除。

在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。

 

示例:

输入:"abbaca" 输出:"ca" 解释: 例如,在 "abbaca" 中,我们可以删除 "bb" 由于两字母相邻且相同,这是此时唯一可以执行删除操作的重复项。之后我们得到字符串 "aaca",其中又只有 "aa" 可以执行重复项删除操作,所以最后的字符串为 "ca"。

来源:力扣(LeetCode)

链接:leetcode-cn.com/problems/re…

 public String removeDuplicates(String s) {
        if (s.length() <=0){
            return s;
        }
        return removeHelper(new StringBuilder(s)).toString();
    }

    static StringBuilder removeHelper(StringBuilder sb) {
        for (int i = 0; i + 1 < sb.length(); i++) {
            if (sb.charAt(i) == sb.charAt(i + 1)) {
                sb.delete(i, i + 2);
                return removeHelper(sb);
            }
        }
        return sb;
    }

7 反转字符串

编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。

不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。

你可以假设数组中的所有字符都是 ASCII 码表中的可打印字符。

作者:力扣 (LeetCode)

链接:leetcode-cn.com/leetbook/re…

class Solution {
    public void reverseString(char[] s) {
        if(s==null || s.length <=0){
            return;
        }
        int start = 0;
        int end = s.length-1;
        
        while (start < end) {
            char temp = s[start];
            s[start++] = s[end];
            s[end--] = temp;
        }
    }
}

8 整数反转

给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。

如果反转后整数超过 32 位的有符号整数的范围 [−231,  231 − 1] ,就返回 0。

假设环境不允许存储 64 位整数(有符号或无符号)。

作者:力扣 (LeetCode)

链接:leetcode-cn.com/leetbook/re…

class Solution {
    public int reverse(int x) {
          int res = 0;
        while (x != 0) {
            int t = x % 10;
            int newRes = res * 10 + t;
            if ((newRes - t) / 10 != res) {
                return 0;
            }
            res = newRes;
            x = x / 10;
        }
        return res;
    }
}
class Solution {
    public int reverse(int x) {
        long result = 0;
        while (x!=0){
            result = result*10+x%10;
            x = x/10;
        }
        if(result<Integer.MIN_VALUE || result> Integer.MAX_VALUE){
            return 0;
        }
        return (int)result;
    }
}

9 字符串中的第一个唯一字符

给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。

示例:

s = "leetcode" 返回 0

s = "loveleetcode" 返回 2  

提示:你可以假定该字符串只包含小写字母。

作者:力扣 (LeetCode)

链接:leetcode-cn.com/leetbook/re…

class Solution {
    public int firstUniqChar(String s) {
        if (s == null || s.length() == 0) {
            return -1;
        }
        HashMap<Character, Integer> map = new HashMap<>();

        char[] chars = s.toCharArray();
        for (Character ch : chars) {
            map.put(ch, map.getOrDefault(ch, 0) + 1);
        }

        for (int i = 0; i < s.length(); i++) {
            if (map.get(s.charAt(i)) == 1) {
                return i;
            }
        }
        return -1;
    }
}

class Solution {
    public int firstUniqChar(String s) {
        if (s == null || s.length() == 0) {
            return -1;
        }
       
       for (int i = 0; i < s.length(); i++) {
            if (s.indexOf(s.charAt(i)) == s.lastIndexOf(s.charAt(i))) {
                return i;
            }
        }
        return -1;

    }
}

10 有效的字母异位词

给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。

示例 1:

输入: s = "anagram", t = "nagaram" 输出: true 示例 2:

输入: s = "rat", t = "car" 输出: false 说明: 你可以假设字符串只包含小写字母。

作者:力扣 (LeetCode)

链接:leetcode-cn.com/leetbook/re…

 public static boolean isAnagram(String s, String t) {
        if (s.length() != t.length()) {
            return false;
        }
        int[] letterCount = new int[26];

        //统计字符串s中的每个字符的数量
        for (int i = 0; i < s.length(); i++) {
            letterCount[s.charAt(i) - 'a']++;
        }

        //减去字符串t中的每个字符的数量
        for (int i = 0; i < t.length(); i++) {
            letterCount[t.charAt(i) - 'a']--;
        }

        //如果数组letterCount的每个值都是0,返回true,否则返回false
        for (int count : letterCount) {
            if (count != 0) {
                return false;
            }
        }
        return true;
    }
    
     public boolean isAnagram(String s, String t) {
       //特判,长度不同必定不是
        if (s.length()!=t.length()) return false;
        //两个字符串排序后是否相等
        char[] array1 = s.toCharArray();
        char[] array2 = t.toCharArray();
        Arrays.sort(array1);
        Arrays.sort(array2);
        return Arrays.equals(array1,array2);
    }
    

11 回文数

**给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。

回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。例如,121 是回文,而 123 不是。

 

示例 1:

输入:x = 121 输出:true

来源:力扣(LeetCode)

链接:leetcode-cn.com/problems/pa…

class Solution {
    public boolean isPalindrome(int x) {
        if(x<0 || (x % 10 == 0 && x!=0)){
            return false;
        }
        int revertNumber = 0;
        while(x>revertNumber){
            revertNumber = revertNumber*10+ x%10;
            x /= 10;
        }
        return x == revertNumber || x == revertNumber/10;
    }
}

12 有效的括号

定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。 左括号必须以正确的顺序闭合。  

示例 1:

输入:s = "()" 输出:true

来源:力扣(LeetCode)

链接:leetcode-cn.com/problems/va…

class Solution {
    public boolean isValid(String s) {
         if (s == null || s.isEmpty() || (s.length() % 2 != 0)) {
            return false;
        }
        char[] chars = s.toCharArray();
        Stack<Character> stack = new Stack<>();
        for (char c : chars) {
            if (c == '(') {
                stack.push(')');
            } else if (c == '[') {
                stack.push(']');
            } else if (c == '{') {
                stack.push('}');
            } else if (stack.isEmpty() || c != stack.pop()) {
                return false;
            }
        }
        return stack.isEmpty();
    }
}