String

Longest Substring Without Repeating Characters

Link: https://leetcode.com/problems/longest-substring-without-repeating-characters/

Code:

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int[] chars = new int[128];
        int n = s.length();
        int res = 0, len = 0;
        int left = 0, right = 0;
        while (right < n) {
            char c = s.charAt(right);
            chars[c]++;
            while (chars[c] > 1) {
                char l = s.charAt(left);
                chars[l]--;
                left++;
            }
            len = right - left + 1;
            res = Math.max(res, len);
            right++;
        }
        return res;
    }
}
  • Sliding Window;

  • Time complexity: O(n);

  • charAt() method for string;

  • length() method for string;

Longest Palindromic Substring

Link: https://leetcode.com/problems/longest-palindromic-substring/

Code:

  • Dynamic programming;

  • Time complexity: O(n^2);

  • Note the i loop is from n-1 to 0, because the transition function needs to know dp[i+1][j-1] first;

  • substring() method for string: to include the last character, substring(i, j+1);

Merge Strings Alternately

Link: https://leetcode.com/problems/merge-strings-alternately/

  • Time complexity: O(n).

Reverse Words in a String

Link: https://leetcode.com/problems/reverse-words-in-a-string/

  • Time complexity: O(n).

  • strip() method for string: remove leading and trailing spaces;

  • split() method for string: split string by a delimiter;

  • join() method for string: join a list of strings by a delimiter;

  • [::-1] for list: reverse a list;

  • [:-1] for list: remove the last element of a list;

  • if word:: check if a string is empty;

Greatest Common Divisor of Strings

Link: https://leetcode.com/problems/greatest-common-divisor-of-strings/

Let m,n be the lengthes of the two input strings str1 and str2.

  • Time complexity: O(m+n)

    • We need to compare the two concatenations of length O(m+n), it takes O(m+n) time.

    • We calculate the GCD using binary Euclidean algorithm, it takes log⁡(m⋅n) time.

    • To sum up, the overall time complexity is O(m+n).

  • Space complexity: O(m+n)

    • We need to compare the two concatenations of length O(m+n).

Last updated