680. Split String

Give a string, you can choose to split the string after one character or two adjacent characters, and make the string to be composed of only one character or two characters. Output all possible results.

Example

Given the string"123"
return[["1","2","3"],["12","3"],["1","23"]]

  • [x] ``` for(int i = startIndex; i < str.length(); i++) {
    String sub = str.substring(startIndex, i+1);
    partition.add(sub);
    dfs(str ... i + 1 ....)
    partition.remove(partition.size() - 1);
    
    } ```
public class Solution {
    /*
     * @param : a string to be split
     * @return: all possible split string array
     */
    public List<List<String>> splitString(String s) {
        // write your code here
        List<List<String>> ans = new ArrayList<>();
        if (s == null) {
            return ans;
        }
        List<String> sub = new ArrayList<>();
        dfs(s, 0, sub, ans);

        return ans;
    }
    public void dfs(String s, int startIndex, List<String> sub, List<List<String>> ans) {
        if (startIndex == s.length()) {
            ans.add(new ArrayList<String>(sub));
            return;
        }
        for (int i = startIndex; i < s.length(); i++ ) {
            String part = s.substring(startIndex, i + 1);
            if (part.length() > 2) {
                continue;
            }
            sub.add(part);
            dfs(s,  i + 1,  sub, ans);
            sub.remove(sub.size() - 1);
        }
    }
}

results matching ""

    No results matching ""