DFS on String
680. Split String (Lintcode)
Split a string into substrings with size of 1 and 2. Use an index pointer to track the start point.
public List<List<String>> splitString(String s) {
List<List<String>> res = new ArrayList<>();
if (s == null || s.isEmpty()) {
return res;
}
dfs(s, 0, res, new ArrayList<>());
return res;
}
private void dfs(String s, int index, List<List<String>> res, List<String> curt) {
if (index == s.length()) {
res.add(new ArrayList<>(curt));
return;
}
for (int i = index + 1; i <= index + 2 && i <= s.length(); i++) {
curt.add(s.substring(index, i));
dfs(s, i, res, curt);
curt.remove(curt.size() - 1);
}
}Backtracking to cut String s into a sub piece which is palindrome. Use a separate function to detect if the string is a palindrome. Use index to mark the current position and when it equals to the original s length, return.
Time complexity: O(n*(2^n))
For a string with length n, there will be (n - 1) intervals between chars.
For every interval, we can cut it or not cut it, so there will be 2^(n - 1) ways to partition the string.
For every partition way, we need to check if it is palindrome, which is O(n). So the time complexity is O(n*(2^n))
Same 131, calculate a min on each level and return an overall min value. Return 0 when index reach length of original s. Also add memo.
给一个目标字符串,从一个段text里面找到,并且返回index。
Followup: 目标字符串可以允许通配符*,代表0或者多个任意字符。比如"*A", 从文档“CDFGAGB”,返回0。比如"A**B",返回4。用递归很好解。
DFS + Memo. DFS breakdown the string into different patterns determine if the string is constructed by the pattern ONLY. If the encoded candidate is shorter than the res, it is a better solution. Also break down the string into two parts and get the candidate from combining the left result and right result.
Last updated
Was this helpful?