Wednesday, May 1, 2019

Lintcode 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

Example1
Input: "123"
Output: [["1","2","3"],["12","3"],["1","23"]]
Example2
Input: "12345"
Output: [["1","23","45"],["12","3","45"],["12","34","5"],["1","2","3","45"],["1","2","34","5"],["1","23","4","5"],["12","3","4","5"],["1","2","3","4","5"]]

Code (Java):

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<>();
        splitStringHelper(s, 0, new ArrayList<String>(), ans);

        return ans;
    }

    private void splitStringHelper(String s, int startIdx, List<String> curList, List<List<String>> ans) {
        if (startIdx >= s.length()) {
            List<String> copy = new ArrayList<>(curList);
            ans.add(copy);
            return;
        }

        for (int i = 1; i <= 2; i++) {
            if (startIdx + i <= s.length()) {
                curList.add(s.substring(startIdx, startIdx + i));
                splitStringHelper(s, startIdx + i, curList, ans);
                curList.remove(curList.size() - 1);
            }
        }
    }
}

No comments:

Post a Comment