find all palidrome string by deleting any letter from the given string
阿新 • • 發佈:2017-12-03
shm const == hashset ring put () rom ive
我就想了個遞歸, 還是沒有區分掉一些重復的情況,worst case O(2^n)基本同暴力解 Map<Integer, Set<String>> allSubSet = new HashMap(); Set<String> getAllPalidrome(String s, int x, int y){ int ind = x * s.length() + y; if(allSubSet.constainsKey(ind)) return allSubSet.get(ind); Set<String> ret = new HashSet(); if (s == null || s.size() == 0) { ret.add(""); return ret;} if (s.size() == 1) { ret.add(s); return ret;} for(int i = x; i <= y; i++){ for (int j = y; j >= i; j--){ if (s.charAt(i) == s.charAt(j)){ Set<String> subSet = getAllPalidrome(s, i + 1, j - 1); ret.addAll(subSet); for (String str : subSet) ret.add(s.charAt(i) + str + s.charAt(i)); } } } allSubSet.put(ind, ret); return ret; }
find all palidrome string by deleting any letter from the given string