4月28号
1 5 Longest Palindromic Substring 分奇偶,找最大

public String longestPalindrome(String s) { int n = s.length(); if (n < 2) return s; String res = ""; for (int i = 0; i < n * 2 - 1; i++) { int l = i / 2, r = i / 2; if (i % 2 == 1) { r++; } String cur = longest(s,l,r); if (res.length() < cur.length()) { res = cur; } } return res; } public String longest(String s, int l, int r) { while (l >=0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--;r++; } return s.substring(l+1,r); }
2 6 ZigZag Conversion n个sb 下上遍历

public String convert(String s, int numRows) { char[] c = s.toCharArray(); int len = c.length; StringBuffer[] sb = new StringBuffer[numRows]; for (int i = 0; i < numRows; i++) { sb[i] = new StringBuffer(); } int i = 0; while (i < len) { for (int ind = 0; ind < numRows && i < len; ind++) { sb[ind].append(c[i++]); } for (int ind = numRows - 2; ind >= 1 && i < len; ind--) { sb[ind].append(c[i++]); } } for (int in = 1; in < numRows; in++) { sb[0].append(sb[in]); } return sb[0].toString(); }
3 10 Regular Expression Match

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()]; }
4 14 Longest Common prefix

public String longestCommonPrefix(String[] strs) { if(strs == null || strs.length == 0) return ""; String pre = strs[0]; int i = 1; while(i < strs.length){ while(strs[i].indexOf(pre) != 0) pre = pre.substring(0,pre.length()-1); i++; } return pre; }
4 月 29 号
5 17 Letter Combination of a Phone number 维护队列 ,遍历数字

public List<String> letterCombinations(String digits) { LinkedList<String> queue = new LinkedList<String>(); if (digits == null || digits.length() == 0) return queue; queue.add(""); String[] map = new String[] {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; for (int i = 0; i < digits.length(); i++) { int x = Character.getNumericValue(digits.charAt(i)); while (queue.peek().length() == i) { String t = queue.remove(); for(char c : map[x].toCharArray()) { queue.add(t + c); } } } return queue; }
6 20 Valid parentheses 维护堆

public boolean isValid(String s) { Stack<Character> stack = new Stack<>(); for (char c : s.toCharArray()) { if (c == '(') { stack.push(')'); } else if (c == '{') { stack.push('}'); } else if (c == '[') { stack.push(']'); } else if (stack.isEmpty() || c != stack.pop()) { return false; } } return stack.isEmpty(); }
7 22 Generate Parentheses 维护栈 ,开括号加 毕小于开

public List<String> generateParenthesis(int n) { List<String> res = new ArrayList<>(); help(n, "", 0, 0, res); return res; } public void help(int n, String item, int open, int close, List<String> res) { if (item.length() == n * 2) { res.add(item); } if (open < n) { help(n, item + "(", open + 1, close, res); } if (close < open) { help(n, item + ")", open, close + 1, res); } }
8 30 Substring with Concatenation of all words hashmap 遍历

public static List<Integer> findSubstring(String S, String[] L) { List<Integer> res = new ArrayList<Integer>(); if (S == null || L == null || L.length == 0) return res; int len = L[0].length(); // length of each word Map<String, Integer> map = new HashMap<String, Integer>(); // map for L for (String w : L) map.put(w, map.containsKey(w) ? map.get(w) + 1 : 1); for (int i = 0; i <= S.length() - len * L.length; i++) { Map<String, Integer> copy = new HashMap<String, Integer>(map); for (int j = 0; j < L.length; j++) { // checkc if match String str = S.substring(i + j*len, i + j*len + len); // next word if (copy.containsKey(str)) { // is in remaining words int count = copy.get(str); if (count == 1) copy.remove(str); else copy.put(str, count - 1); if (copy.isEmpty()) { // matches res.add(i); break; } } else break; // not in L } } return res; }
5 月 1 号
9 32 Longest Valid Parentheses 维护堆和一个开始

public int longestValidParentheses(String s) { Stack<Integer> stack = new Stack<>(); int start = 0, max = 0; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == '(') { stack.push(i); } else { if (stack.isEmpty()) { start = i + 1; } else { stack.pop(); int curMax = stack.isEmpty() ? i - start + 1: i - stack.peek(); max = Math.max(max, curMax); } } } return max; }
10 38 Count and say 遍历 维护stringbuilder

public String countAndSay(int n) { if (n < 1) return ""; String str = "1"; for (int i = 2; i <= n; i++) { StringBuilder sb = new StringBuilder(); int count = 1; for (int j = 1; j < str.length(); j++) { if (str.charAt(j) == str.charAt(j - 1)) { count++; } else { sb.append(count); sb.append(str.charAt(j - 1)); count = 1; } } sb.append(count); sb.append(str.charAt(str.length() - 1)); str = sb.toString(); } return str; }
11 49 Group Anagrams 维护hashmap

public List<List<String>> groupAnagrams(String[] strs) { if (strs == null || strs.length == 0) return new ArrayList<List<String>>(); HashMap<String, List<String>> map = new HashMap<>(); for (int i = 0; i < strs.length; i++) { char[] c = strs[i].toCharArray(); Arrays.sort(c); String cur = String.valueOf(c); if (!map.containsKey(cur)) map.put(cur, new ArrayList<String>()); map.get(cur).add(strs[i]); } return new ArrayList<List<String>>(map.values()); }
12 58 Length of Last Word

public int lengthOfLastWord(String s) { return s.trim().length() - s.trim().lastIndexOf(" ") - 1; }
5 月 2 号
13 71 Simple path 双端队列

public String simplifyPath(String path) { Deque<String> stack = new LinkedList<>(); HashSet<String> set = new HashSet<>(Arrays.asList("..",".","")); for (String str : path.split("/")){ if (str.equals("..") && !stack.isEmpty()) stack.pop(); else if (!set.contains(str)) stack.push(str); } String res = ""; for (String dir : stack) res = "/" + dir + res; return res.isEmpty()? "/" : res; }
14 91 Decode Ways 斐波纳数列

public int numDecodings(String s) { if (s.isEmpty() || (s.length() > 1 && s.charAt(0) == '0')) return 0; int[] dp = new int[s.length() + 1]; dp[0] = 1; for (int i = 1; i < dp.length; i++) { dp[i] = s.charAt(i - 1) == '0'? 0 : dp[i - 1]; if (i > 1 && (s.charAt(i - 2) == '1' || (s.charAt(i - 2) == '2'&& s.charAt(i - 1) <= '6'))) { dp[i] += dp[i - 2]; } } return dp[s.length()]; }

public int numDecodings(String s) { if (s.isEmpty() || s.charAt(0) == '0') return 0; int c1 = 1, c2 = 1; for (int i = 1; i < s.length(); i++) { if (s.charAt(i) == '0') c1 = 0; if (s.charAt(i - 1) == '1' || s.charAt(i - 1) == '2' && s.charAt(i) <= '6') { c1 = c1 + c2; c2 = c1 - c2; } else { c2 = c1; } } return c1; }
15 93 Restore IP Addresses 4个循环

public List<String> restoreIpAddresses(String s) { List<String> list = new ArrayList<>(); for (int i = 1; i < 4 && i < s.length() - 2; i++) { for (int j = i + 1; j < i + 4 &&j < s.length() - 1; j++) { for (int k = j + 1; k < j + 4 && k < s.length(); k++) { String s1 = s.substring(0,i), s2 = s.substring(i,j), s3 = s.substring(j,k), s4 = s.substring(k,s.length()); if (is(s1) && is(s2) && is(s3) && is(s4)) { list.add(s1 +"."+ s2 + "."+s3 + "."+s4); } } } } return list; } public boolean is(String s){ if(s.length()>3 || s.length()==0 || (s.charAt(0)=='0' && s.length()>1) || Integer.parseInt(s)>255) return false; return true; }
16 97 Interleaving String 动态规划

public boolean isInterleave(String s1, String s2, String s3) { if (s1.length() + s2.length() != s3.length()) return false; boolean[][] res = new boolean[s1.length() + 1][s2.length() + 1]; for (int i = 0; i < s1.length() + 1; i++) { for (int j = 0; j < s2.length() + 1; j++) { if (i == 0 && j == 0) { res[i][j] = true; } else if (i == 0) { res[i][j] = res[i][j - 1] && s2.charAt(j - 1) == s3.charAt(i + j - 1); } else if (j == 0) { res[i][j] = res[i - 1][j] && s1.charAt(i - 1) == s3.charAt(i + j - 1); } else { res[i][j] = res[i - 1][j] && s1.charAt(i - 1) == s3.charAt(i + j - 1) || res[i][j - 1] && s2.charAt(j - 1) == s3.charAt(i + j - 1); } } } return res[s1.length()][s2.length()]; }
5 月 3 号
17 115 Distinct Subsequences

public int numDistinct(String s, String t) { int[][] res = new int[t.length() + 1][s.length() + 1]; for (int i = 0; i < s.length() + 1; i++) { res[0][i] = 1; } for (int i = 0; i < t.length(); i++) { for (int j = 0; j < s.length(); j++) { if (t.charAt(i) != s.charAt(j)) { res[i + 1][j + 1] = res[i + 1][j]; } else { res[i + 1][j + 1] = res[i + 1][j] + res[i][j]; } } } return res[t.length()][s.length()]; }
18 151 Reverse Words in a String 切分,反转,加入

public String reverseWords(String s) { String[] words = s.trim().split(" +"); Collections.reverse(Arrays.asList(words)); return String.join(" ", words); }
19 157 Read N Characters Given read4

public class Solution extends Reader4 { public int read(char[] buf, int n) { for(int i = 0; i < n; i += 4){ char[] tmp = new char[4]; // 将数据读入临时数组 int len = read4(tmp); // 将临时数组拷贝至buf数组,这里拷贝的长度是本次读到的个数和剩余所需个数中较小的 System.arraycopy(tmp, 0, buf, i, Math.min(len, n - i)); // 如果读不满4个,说明已经读完了,返回总所需长度和目前已经读到的长度的较小的 if(len < 4) return Math.min(i + len, n); } // 如果循环内没有返回,说明读取的字符是4的倍数 return n; } }
20 158 Read N Characters Given read4 II

public class Solution extends Reader4 { Queue<Character> remain = new LinkedList<Character>(); public int read(char[] buf, int n) { int i = 0; // 队列不为空时,先读取队列中的暂存字符 while(i < n && !remain.isEmpty()){ buf[i] = remain.poll(); i++; } for(; i < n; i += 4){ char[] tmp = new char[4]; int len = read4(tmp); // 如果读到字符多于我们需要的字符,需要暂存这些多余字符 if(len > n - i){ System.arraycopy(tmp, 0, buf, i, n - i); // 把多余的字符存入队列中 for(int j = n - i; j < len; j++){ remain.offer(tmp[j]); } // 如果读到的字符少于我们需要的字符,直接拷贝 } else { System.arraycopy(tmp, 0, buf, i, len); } // 同样的,如果读不满4个,说明数据已经读完,返回总所需长度和目前已经读到的长度的较小的 if(len < 4) return Math.min(i + len, n); } // 如果到这里,说明都是完美读取,直接返回n return n; } }
5月 4 号
21 161 one edit distance 遍历,找到相同字符

public boolean isOneEditDistance(string s, string t) { int m = s.length(), n = t.length(); for (int i = 0; i < Math.min(m, n); i++) { if (s.charAt(i) != t.charAt(i)) { if (m == n) return s.substring(i + 1).equals(t.substring(i + 1)); else if (m > n) return s.substring(i + 1).equals(t.substring(i)); else return s.substring(i).equals(t.substring(i + 1)); } } return Math.abs(m - n) == 1; }
22 165 Compare Version Numbers 切分,比较

public int compareVersion(String version1, String version2) { String[] l1 = version1.split("\."); String[] l2 = version2.split("\."); int len = Math.max(l1.length, l2.length); for (int i = 0; i < len; i++) { Integer v1 = i < l1.length ? Integer.parseInt(l1[i]) : 0; Integer v2 = i < l2.length ? Integer.parseInt(l2[i]) : 0; int com = v1.compareTo(v2); if (com != 0) return com; } return 0; }
23 186 Reverse words in a string iI 反转全部,一个一个反转

1 public void reverseWords(char[] s) { 2 // Three step to reverse 3 // 1, reverse the whole sentence 4 reverse(s, 0, s.length - 1); 5 // 2, reverse each word 6 int start = 0; 7 int end = -1; 8 for (int i = 0; i < s.length; i++) { 9 if (s[i] == ' ') { 10 reverse(s, start, i - 1); 11 start = i + 1; 12 } 13 } 14 // 3, reverse the last word, if there is only one word this will solve the corner case 15 reverse(s, start, s.length - 1); 16 } 17 18 public void reverse(char[] s, int start, int end) { 19 while (start < end) { 20 char temp = s[start]; 21 s[start] = s[end]; 22 s[end] = temp; 23 start++; 24 end--; 25 } 26 }
24 214 Shortest Palindrome end i j 找从开头最短

public String shortestPalindrome(String s) { char[] c = s.toCharArray(); int i = 0, j = c.length - 1, end = j; while (i < j) { if (c[i] == c[j]) { i++;j--; } else { i = 0; end--; j = end; } } return new StringBuilder(s.substring(end + 1)).reverse().toString() + s; }
5月5号
25 227 Basic Calculator II 栈 遇到符号加入

int len; if(s==null || (len = s.length())==0) return 0; Stack<Integer> stack = new Stack<Integer>(); int num = 0; char sign = '+'; for(int i=0;i<len;i++){ if(Character.isDigit(s.charAt(i))){ num = num*10+s.charAt(i)-'0'; } if((!Character.isDigit(s.charAt(i)) &&' '!=s.charAt(i)) || i==len-1){ if(sign=='-'){ stack.push(-num); } if(sign=='+'){ stack.push(num); } if(sign=='*'){ stack.push(stack.pop()*num); } if(sign=='/'){ stack.push(stack.pop()/num); } sign = s.charAt(i); num = 0; } } int re = 0; for(int i:stack){ re += i; } return re;
26 249 group shifted string (a[j] - a[0] + 26)%26

public List<List<String>> groupStrings(String[] strings) { List<List<String>> result = new ArrayList<List<String>>(); HashMap<String, List<String>> d = new HashMap<>(); for(int i = 0; i < strings.length; i++) { StringBuffer sb = new StringBuffer(); for(int j = 0; j < strings[i].length(); j++) { sb.append(Integer.toString(((strings[i].charAt(j) - strings[i].charAt(0)) + 26) % 26)); sb.append(" "); } String shift = sb.toString(); if(d.containsKey(shift)) { d.get(shift).add(strings[i]); } else { List<String> l = new ArrayList<>(); l.add(strings[i]); d.put(shift, l); } } for(String s : d.keySet()) { Collections.sort(d.get(s)); result.add(d.get(s)); } return result; }