String brush notes

Posted by junrey on Sat, 19 Feb 2022 19:04:40 +0100

String brush notes

541.Reverse string II

code implementation

class Solution {
    public String reverseStr(String s, int k) {
        char[] a = s.toCharArray();
	    int i = 0;
	    int j = 0;
	    char tmp;
        for (int start = 0; start < a.length; start += 2 * k) {
            i = start;
            // Ensure the requirements of the topic, and all characters less than k are reversed
	        j = Math.min(start + k - 1, a.length - 1);
            while (i < j) {
                tmp = a[i];
                a[i++] = a[j];
                a[j--] = tmp;
            }
        }
        return new String(a);
    }
}

151.Flip the words in the string

API Player Special Edition

class Solution {
    public String reverseWords(String s) {
        // Remove white space characters at the beginning and end
        s = s.trim();
        // Regular matching uses continuous white space characters as separators
        List<String> wordList = Arrays.asList(s.split("\\s+"));
        Collections.reverse(wordList);
        // Add a space as a separator in the middle of each string
        return String.join(" ", wordList);
    }
}

Expand - use additional space to achieve

class Solution {
    public String reverseWords(String s) {
        // Because the final result string needs to be constantly modified, StringBuilder is selected for convenience
        StringBuilder res = new StringBuilder();
        // Clear excess space at beginning and end
        String validStr = s.trim();
        // Separate each string with a space and output it as an array
        String[] split = validStr.split(" ");
        // Traverse the array and output it to the object initialized by StringBuilder in reverse order
        for (int i = split.length-1; i >= 0 ; i--) {
            if(split[i].trim().length() > 0){
                res.append(split[i]);
                // Add a space to each string. Pay attention to the details. The judgment condition means to add a space after each time, so the penultimate one does not need to add a space
                if(i != 0){
                    res.append(" ");
                }
            }            
        }
        return res.toString();
    }
}

Sword finger Offer 58 - II Left rotation string

String slicing

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

List traversal splicing

class Solution {
    public String reverseLeftWords(String s, int n) {
        StringBuilder res = new StringBuilder();
        for(int i = n; i < s.length(); i++)
            res.append(s.charAt(i));
        for(int i = 0; i < n; i++)
            res.append(s.charAt(i));
        return res.toString();
    }
}

simplify

class Solution {
    public String reverseLeftWords(String s, int n) {
        StringBuilder res = new StringBuilder();
        for(int i = n; i < n + s.length(); i++)
            res.append(s.charAt(i % s.length()));
        return res.toString();
    }
}

Of course, the String class can also be implemented, but it only affects the performance. It depends on the requirements of the interviewer.

class Solution {
    public String reverseLeftWords(String s, int n) {
        String res = "";
        for(int i = n; i < s.length(); i++)
            res += s.charAt(i);
        for(int i = 0; i < n; i++)
            res += s.charAt(i);
        return res;
    }
}

459. Duplicate substring

Compact code version

Ideas and code implementation

If your string S contains a repeated substring, this means that you can "shift and wrap" your string multiple times and match it with the original string.

For example: abcabc

Shift once: cabcab
Shift twice: bcabca
Shift three times: abcabc

Now that the string matches the original string, it can be concluded that there are duplicate substrings.

Based on this idea, you can move k characters at a time until it matches and moves length - 1 times. However, this will be very inefficient for strings with long repeated strings. The execution time in LeetCode timed out.

To avoid this useless wrapping, you can create a new string str, which is equal to the original string S plus S itself, so that it actually contains all the moving strings.

For example, string: S = acd, then str = S + S = acdacd

The possibility of acd moving: dac, cda. In fact, they are all included in str. Like a sliding window

At the beginning of acd (acd), move ac(dac)d once and a(cda)cd twice. End of cycle

Therefore, you can directly judge whether str contains its own elements after removing the first and last elements. If included. It indicates that there is a duplicate substring.

——From leetcode

class Solution {
   public boolean repeatedSubstringPattern(String s) {
        String str = s + s;
        return str.substring(1, str.length() - 1).contains(s);
	}
}

However, this method needs to prove the sufficient and necessary superposition of two s strings, and there are many details. Don't repeat. The official website is very clear. I don't remember to look at it again.

Optimized KMP algorithm

class Solution {
    public boolean repeatedSubstringPattern(String s) {
        return kmp(s);
    }

    public boolean kmp(String pattern) {
        int n = pattern.length();
        int[] fail = new int[n];
        Arrays.fill(fail, -1);
        for (int i = 1; i < n; ++i) {
            int j = fail[i - 1];
            while (j != -1 && pattern.charAt(j + 1) != pattern.charAt(i)) {
                j = fail[j];
            }
            if (pattern.charAt(j + 1) == pattern.charAt(i)) {
                fail[i] = j + 1;
            }
        }
        return fail[n - 1] != -1 && n % (n - fail[n - 1] - 1) == 0;
    }
}

If you want to thoroughly understand and master the KMP algorithm, you must read more obscure books and principles. It is recommended that readers take a look at the KMP algorithm of Wangdao postgraduate entrance examination, which is convenient and fast to master. I won't repeat it here. I can't make it clear. The code is only for your review.

Topics: string