String
Longest Substring Without Repeating Characters
Link: https://leetcode.com/problems/longest-substring-without-repeating-characters/
Code:
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 fromn-1
to0
, because the transition function needs to knowdp[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