The sword refers to the offer-of-string

Jianzhi offer brushing notes – string

5. Difficulty of replacing spaces: easy

This question is relatively simple. The overall idea is to first define a string of StringBuffer type, convert the string into a character array and traverse it once. When a space is encountered, add "%20" to the newly defined string, otherwise directly add it to the current The characters traversed can be used. Note that the StringBuffer type must be converted to a String type at the end.

class Solution {
    
    
    public String replaceSpace(String s) {
    
    
        StringBuffer res = new StringBuffer();
        for(char c : s.toCharArray()){
    
    
            if(c == ' '){
    
    
                res.append("%20");
            }else{
    
    
                res.append(c);
            }
        }
        return res.toString();
    }
}

38. Difficulty of arranging strings: medium

The main idea of ​​this question is backtracking + pruning. Backtracking is achieved through recursion, and pruning is because the same characters may exist in the string, so HashSet needs to be used to judge repeated characters and then pruned.

class Solution {
    
    
    char[] c;
    List<String> res = new ArrayList<>();
    public String[] permutation(String s) {
    
    
        c = s.toCharArray();
        dfs(0);
        return res.toArray(new String[res.size()]);
    }
    public void dfs(int x){
    
    
        if(x == c.length-1){
    
    
            res.add(String.valueOf(c));
            return;
        }
        Set<Character> set = new HashSet<>();
        for(int i = x; i<c.length;++i){
    
    
            if(set.contains(c[i]))  continue;
            set.add(c[i]);
            swap(x,i);
            dfs(x+1);
            swap(x,i);
        }
    }
    public void swap(int a, int b){
    
    
        char tmp = c[a];
        c[a] = c[b];
        c[b] = tmp;
    }
}

45. Arrange the array into the smallest number Difficulty: Medium

In this question, you can convert the integer array into a string array, and then sort the array through our rewritten sorting method. After the sorting is completed, convert the string array into a string and return it.

We define the sort as follows:

Let x and y be two numeric strings, if x+y > y+x, then x should be arranged after y, otherwise x should be arranged before y.

Here x+y and y+x represent the actual numbers formed by these two strings.

Such as "(1"+"2" = 12) < ("2"+"1"=21)

class Solution {
    
    
    public String minNumber(int[] nums) {
    
    
        String[] strs = new String[nums.length];
        for(int i = 0;i<nums.length;++i){
    
    
            strs[i] = String.valueOf(nums[i]);
        }
        Arrays.sort(strs,(x,y)->(x+y).compareTo(y+x));
        StringBuffer res = new StringBuffer();
        for(String s : strs){
    
    
            res.append(s);
        }
        return res.toString();
    }
}

46. ​​Translate numbers into strings Difficulty: Moderate

The main idea of ​​this question is dynamic programming. By converting numbers into strings and traversing from beginning to end, all translation methods are obtained through the idea of ​​dynamic programming. The specific operation is similar to the problem of "frog jumping steps". There are two differences:

1. In the process of traversing the string, each time it is necessary to judge whether the combination of the current character and the previous character is between 10 and 25. If it is within this range, then dp[i] = dp[i- 1]+dp[i-2], otherwise dp[i] = dp[i-1].

2. During initialization, the reason for setting the translation method of 0 digits to 1 is: if the number composed of the first two characters in the string is between 10 and 25, it means that dp[1] = 2, but dp[0 ] = 1, so we set dp[-1] = 1;

dp[i] represents the total number of translation methods in the string ending with the character corresponding to the i subscript.

class Solution {
    
    
    public int translateNum(int num) {
    
    
        String s = String.valueOf(num);
        int a = 1;//设0位数时的翻译方法为1
        int b = 1;//1位数时的翻译方法为1
        for(int i = 2; i <= s.length();++i){
    
    
            String tmp = s.substring(i-2,i);
            int c = (tmp.compareTo("10")>=0 && tmp.compareTo("25")<=0) ? a+b : a;
            b = a;
            a = c;
        }
        return a;
    }
}

48. Longest substring without repeating characters Difficulty: Moderate

The main idea of ​​this question is dynamic programming, but a hash table is needed to store data. tmp is the maximum length of the longest non-repeating character string whose end is the current character, and res is the maximum length of the longest non-repeating character string currently traversed.

Key stored in the hash table: the character in the string, value: the subscript of the character in the string.

Because characters may be repeated, when a repeated character is traversed, the value of the character in the hash table will be refreshed, and i is the subscript of the character before this refresh, then the current i and j correspond is the subscript of the same two characters in the string, and j - i is the length of the character string ending j 对应的字符with .

But there may be other repeated characters in the string ji, so we compare tmp with ji, refresh the value of tmp, and let tmp store it 不含重复字符的子字符串长度.

If it tmp >= j - imeans that the string corresponding to ji is in the string corresponding to tmp, then refresh tmp to ji.

If tmp < j - iit means that the string corresponding to j - i contains the string corresponding to tmp, then there must be repeated characters in ji, so tmp cannot be refreshed to ji, and only tmp+1 is required.

class Solution {
    
    
    public int lengthOfLongestSubstring(String s) {
    
    
        Map<Character,Integer> map = new HashMap<>();
        int tmp = 0;
        int res = 0;
        for(int j = 0; j < s.length(); ++j){
    
    
            int i = map.getOrDefault(s.charAt(j),-1);
            map.put(s.charAt(j),j);
            tmp = (tmp < j-i) ? tmp+1 : j-i;
            res = Math.max(res,tmp);
        }
        return res;
    }
}

58. Flip Word Order I Difficulty: Easy

This question uses the double pointer method: create two pointers i and j, pointing to the beginning and end of each word respectively, traverse from back to front, and add words one by one to the newly created string through two pointers. The points to be noted are To remove the leading and trailing spaces of the string first.

class Solution {
    
    
    public String reverseWords(String s) {
    
    
        s = s.trim();//删除首尾空格
        int i = s.length()-1;
        int j = i;
        StringBuffer res = new StringBuffer();
        while(i >= 0){
    
    
            while(i >= 0 && s.charAt(i) != ' ')     i--;//找到单词的头部
            res.append(s.substring(i+1,j+1)+" ");		//将单词加入res中
            while(i >= 0 && s.charAt(i) == ' ')     i--;//找到单词的尾部
            j=i;								//让j指向单词尾部
        }
        return res.toString().trim();
    }
}
 

58. Left Rotate String II Difficulty: Easy

This question can be completed with the operation of splitting the string. It should be noted that: the function range of the substring() method is left-closed and right-opened.

lass Solution {
    
    
    public String reverseLeftWords(String s, int n) {
    
    
        int len = s.length();
        return s.substring(n,len)+s.substring(0,n);
    }
}

Part of the code refers to LeetCode Author: Krahets

Guess you like

Origin blog.csdn.net/m0_52373742/article/details/121255438