Table of Contents
5. Longest Palindromic Substring
10. Regular Expression Matching
17. Letter Combinations of a Phone Number
19. Remove Nth Node From End of List
5. Longest Palindromic Substring
https://leetcode.com/problems/longest-palindromic-substring/
String, Expand around center 中心开花
Time: O(n2) Space: constant
class Solution {
public String longestPalindrome(String s) {
if(s == null || s.length() <= 1) {
return s;
}
int max = 0;
String res = "";
char[] sc = s.toCharArray();
for (int i = 0; i < s.length() - 1; i++) {
if(max < lengthOfPalindrome(sc, i, i + 1)) {
max = lengthOfPalindrome(sc, i, i + 1);
res = new String(sc, i - (max - 2) / 2, max);
}
if(max < lengthOfPalindrome(sc, i, i)) {
max = lengthOfPalindrome(sc, i, i);
res = new String(sc, i - (max - 1) / 2, max);
}
}
return res;
}
public int lengthOfPalindrome(char[] sc, int i, int j) {
if(i >= 0 && j < sc.length) {
if(sc[i] == sc[j]) {
return lengthOfPalindrome(sc, i - 1, j + 1);
}
}
return j - i + 1 - 2;
}
}
10. Regular Expression Matching
Hard - https://leetcode.com/problems/regular-expression-matching
Given an input string (s
) and a pattern (p
), implement regular expression matching with support for '.'
and '*'
.
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
Example 1:
Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".
Example 2:
Input:
s = "aa"
p = "a*"
Output: true
Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".
Example 3:
Input:
s = "ab"
p = ".*"
Output: true
Explanation: ".*" means "zero or more (*) of any character (.)".
Example 4:
Input:
s = "aab"
p = "c*a*b"
Output: true
Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore, it matches "aab".
Example 5:
Input:
s = "mississippi"
p = "mis*is*p*."
Output: false
DP - 2D
1, If p.charAt(j) == s.charAt(i) : dp[i][j] = dp[i-1][j-1];
2, If p.charAt(j) == '.' : dp[i][j] = dp[i-1][j-1];
3, If p.charAt(j) == '*':
here are two sub conditions:
1 if p.charAt(j-1) != s.charAt(i) : dp[i][j] = dp[i][j-2] //in this case, a* only counts as empty
2 if p.charAt(i-1) == s.charAt(i) or p.charAt(i-1) == '.':
dp[i][j] = dp[i-1][j] //in this case, a* counts as multiple a
or dp[i][j] = dp[i][j-1] // in this case, a* counts as single a
or dp[i][j] = dp[i][j-2] // in this case, a* counts as empty
Time: O(s x p); Space: O(s x p)
class Solution {
public boolean isMatch(String s, String p) {
if (s == null || p == null) {
return false;
}
boolean[][] dp = new boolean[s.length()+1][p.length()+1];
dp[0][0] = true;
for (int i = 0; i < p.length(); i++) {
if (p.charAt(i) == '*' && dp[0][i-1]) {
dp[0][i+1] = true;
}
}
for (int i = 0 ; i < s.length(); i++) {
for (int j = 0; j < p.length(); j++) {
if (p.charAt(j) == '.') {
dp[i+1][j+1] = dp[i][j];
}
if (p.charAt(j) == s.charAt(i)) {
dp[i+1][j+1] = dp[i][j];
}
if (p.charAt(j) == '*') {
if (p.charAt(j-1) != s.charAt(i) && p.charAt(j-1) != '.') {
dp[i+1][j+1] = dp[i+1][j-1];
} else {
dp[i+1][j+1] = (dp[i+1][j] || dp[i][j+1] || dp[i+1][j-1]);
}
}
}
}
return dp[s.length()][p.length()];
}
}
11. Container With Most Water
https://leetcode.com/problems/container-with-most-water/
Two pointers
Time: O(n), Space: O(1)
class Solution {
public int maxArea(int[] height) {
int left = 0;
int right = height.length - 1;
int maxArea = 0;
while (left < right) {
int area = (right - left) * Math.min(height[right], height[left]);
maxArea = Math.max(area, maxArea);
if (height[right] < height[left]) {
right--;
} else {
left++;
}
}
return maxArea;
}
}
15. 3Sum
https://leetcode.com/problems/3sum/
Sort first(O(nlogn)), Two pointers
iteraion: O(n2), Sort Array: O(nlogn)
Time: O(n2), Space: O(1)
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
for(int i = 0; i < nums.length; i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int target = 0 - nums[i];
int left = i + 1;
int right = nums.length - 1;
while(left < right) {
if(nums[left] + nums[right] == target) {
res.add(Arrays.asList(nums[i], nums[left], nums[right]));
left++;
right--;
while(left < right && nums[right] == nums[right + 1]){
right--;
}
while(left < right && nums[left] == nums[left - 1]) {
left++;
}
} else if (nums[left] + nums[right] < target) {
left++;
} else {
right--;
}
}
}
return res;
}
}
17. Letter Combinations of a Phone Number
https://leetcode.com/problems/letter-combinations-of-a-phone-number/
Backtracking, Combination
Time: levels of recursion (stack) -> O(3^n) n is total number of digits
Space: same as Time
class Solution {
final public String[] phoneLetters = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
public List<String> letterCombinations(String digits) {
if(digits == null || digits.length() == 0) {
return new ArrayList<>();
}
List<String> res = new ArrayList<>();
StringBuilder sb = new StringBuilder();
dfs(digits, 0, res, sb);
return res;
}
public void dfs(String digits, int index, List<String> res, StringBuilder sb) {
if(index >= digits.length()) {
res.add(sb.toString());
return;
}
char[] chars = phoneLetters[digits.charAt(index) - '2'].toCharArray();
for(char c : chars) {
sb.append(c);
dfs(digits, index + 1, res, sb);
sb.deleteCharAt(sb.length() - 1);
}
}
}
19. Remove Nth Node From End of List
https://leetcode.com/problems/remove-nth-node-from-end-of-list/
Two pointers (fast, slow), dummyHead to prevent Null
Time: O(n) - one pass
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummyHead = new ListNode(0);
dummyHead.next = head;
ListNode slow = dummyHead;
ListNode fast = dummyHead;
for(int i = 0; i < n + 1; i++) {
fast = fast.next;
}
while(fast != null) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return dummyHead.next;
}
}
20. Valid Parentheses
https://leetcode.com/problems/valid-parentheses/
Stack
Time: O(n)
Space: Map to lookup pairs, O(1)
class Solution {
static final private Map<Character, Character> PAIRS = new HashMap<>();
static {
PAIRS.put(')', '(');
PAIRS.put('}', '{');
PAIRS.put(']', '[');
}
public boolean isValid(String s) {
if(s.length() == 0) {
return true;
}
Deque<Character> stack = new ArrayDeque<>();
for(int i = 0; i < s.length(); i++) {
char cur = s.charAt(i);
if (cur == '(' || cur == '{' || cur == '[') {
stack.push(cur);
} else {
if(stack.isEmpty() || stack.pop() != PAIRS.get(cur)) {
return false;
}
}
}
return stack.isEmpty();
}
}