publicintnumDecodings(String s) { return recursiveWithMemo(0, s); } privateintrecursiveWithMemo(int index, String str) { // Have we already seen this substring? if (memo.containsKey(index)) { return memo.get(index); } // If you reach the end of the string // Return 1 for success. if (index == str.length()) { return1; }
// If the string starts with a zero, it can't be decoded if (str.charAt(index) == '0') { return0; }
if (index == str.length() - 1) { return1; }
intans= recursiveWithMemo(index + 1, str); if (Integer.parseInt(str.substring(index, index + 2)) <= 26) { ans += recursiveWithMemo(index + 2, str); }
publicintnumDecodings(String s) { // DP array to store the subproblem results int[] dp = newint[s.length() + 1]; dp[0] = 1; // Ways to decode a string of size 1 is 1. Unless the string is '0'. // '0' doesn't have a single digit decode. dp[1] = s.charAt(0) == '0' ? 0 : 1;
for(inti=2; i < dp.length; i++) { // Check if successful single digit decode is possible. if (s.charAt(i - 1) != '0') { dp[i] = dp[i - 1]; } // Check if successful two digit decode is possible. inttwoDigit= Integer.valueOf(s.substring(i - 2, i)); if (twoDigit >= 10 && twoDigit <= 26) { dp[i] += dp[i - 2]; } } return dp[s.length()]; } }
We usually utilize stack when we face problems related to parenthesis. And it’s time to do with the elements lying in the stack if we meet ‘)’.
In this case, the element we popped should be left child of the element on top of the stack if there is no left child yet, or else, it will be the right child. Please note that if there is only one node, i.e., the root of the Binary Tree, then the element on top of the stack is the root. Or else, the pointer parent points to the root in the last.
public String reverseWords(String s) { //the sky is blue //eulb si yks eth //blue is sky the StringBuilder sb=newStringBuilder(); s=s.trim(); for (inti=0; i < s.length(); i++) { sb.append(s.charAt(i)); } String[] words = sb.reverse().toString().split("\\s+"); sb=newStringBuilder(); for (String word : words) { for (inti= word.length()-1; i >= 0; i--) { sb.append(word.charAt(i)); } sb.append(" "); } sb.deleteCharAt(sb.length()-1); return sb.toString(); }
// Ensure that s is shorter than t. if (ns > nt) return isOneEditDistance(t, s);
// The strings are NOT one edit away distance // if the length diff is more than 1. if (nt - ns > 1) returnfalse;
for (inti=0; i < ns; i++) if (s.charAt(i) != t.charAt(i)) // if strings have the same length if (ns == nt) return s.substring(i + 1).equals(t.substring(i + 1)); // if strings have different lengths else return s.substring(i).equals(t.substring(i + 1));
// If there is no diffs on ns distance // the strings are one edit away only if // t has one more character. return (ns + 1 == nt); } }
165. Compare Version Numbers
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
publicintcompareVersion(String version1, String version2) { //注意:regex中,"." means any character //"\\." means dot //"\\s+" means one or many space String[] arr1 = version1.split("\\."); String[] arr2 = version2.split("\\."); int i=0; while(i<arr1.length || i<arr2.length){ int a= i<arr1.length ? Integer.parseInt(arr1[i]) : 0; int b= i<arr2.length ? Integer.parseInt(arr2[i]) : 0; if(a>b){ return1; }elseif(a<b){ return -1; } i++; } return0; }
publicvoidreverseWords(char[] s) { //the sky is blue //eulb si yks eht //blue is sky the int n=s.length; int l=0; int r=n-1; while(l<r){ swap(s,l++,r--); } l=0; for (inti=0; i < n; i++) { if(s[i]==' '){ r=i-1; while(l<r){ swap(s,l++,r--); } l=i+1; } } r=n-1; while(l<r){ swap(s,l++,r--); } }
voidswap(char[] s, int l ,int r){ char temp=s[l]; s[l]=s[r]; s[r]=temp; }
187. Repeated DNA Sequences
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
public List<String> findRepeatedDnaSequences(String s) { List<String> res=newArrayList<>(); Map<String,Integer> map=newHashMap<>(); int n=s.length(); for (inti=0; i <= n-10; i++) { //[i,i+10) //[n-10,n) String cur=s.substring(i,i+10); map.put(cur,map.getOrDefault(cur,0)+1); if(map.get(cur)==2){ res.add(cur); } } return res; }
public List<List<String>> groupStrings(String[] strings) { Map<String, List<String>> map= newHashMap<>(); for (String s : strings) { String t=transform(s); map.putIfAbsent(t,newLinkedList<>()); map.get(t).add(s); } returnnewLinkedList<>(map.values()); }
String transform(String s){ StringBuilder sb=newStringBuilder(); int n=s.length(); int shift=s.charAt(0)-'a'; for (inti=0; i < n; i++) { char c=s.charAt(i); //'z'=('a'+25) char t=(c-shift>='a') ? (char)(c-shift) : (char)(c-shift+26); sb.append(t); } return sb.toString(); }
266. Palindrome Permutation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
public boolean canPermutePalindrome(String s) { int[] arr=new int[26]; int n=s.length(); for (int i = 0; i < n; i++) { arr[s.charAt(i)-'a']++; } int c=0; for (int i = 0; i < 26; i++) { if((arr[i]&1)!=0){ c++; if(c>1){ return false; } } } return c<=1; }
booleanisMatch(String str, int i, String pat, int j, Map<Character, String> map, Set<String> set) { // base case if (i == str.length() && j == pat.length()) returntrue; if (i == str.length() || j == pat.length()) returnfalse; // get current pattern character charc= pat.charAt(j); // if the pattern character exists if (map.containsKey(c)) { Strings= map.get(c); // then check if we can use it to match str[i...i+s.length()] if (!str.startsWith(s, i)) { returnfalse; } // if it can match, great, continue to match the rest return isMatch(str, i + s.length(), pat, j + 1, map, set); } // pattern character does not exist in the map for (intk= i; k < str.length(); k++) { Stringp= str.substring(i, k + 1);
if (set.contains(p)) { continue; }
// create or update it map.put(c, p); set.add(p); // continue to match the rest if (isMatch(str, k + 1, pat, j + 1, map, set)) { returntrue; }
// backtracking map.remove(c); set.remove(p); } // we've tried our best but still no luck returnfalse; }