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"]]

思路:选1或者选2

public class Solution {
    /*
     * @param : a string to be split
     * @return: all possible split string array
     */
    public List<List<String>> splitString(String s) {
        List<List<String>> lists = new ArrayList<List<String>>();
        if(s == null) return lists;
        List<String> list = new ArrayList<String>();
        dfs(s, 0, list, lists);
        return lists;
    }
    
    private void dfs(String s, int index, List<String> list, List<List<String>> lists) {
        if(index == s.length()){
            lists.add(new ArrayList<String>(list));
            return;
        }
       
        // choose 1;
        list.add(s.substring(index, index+1));
        // explore
        dfs(s, index+1, list, lists);
        // unchoose 1;
        list.remove(list.size() -1);

        if(index+2 <= s.length()) {
            // choose 2;
            list.add(s.substring(index, index+2));
            // explore
            dfs(s, index+2, list, lists);
            // unchoose 2;
            list.remove(list.size() -1);
        }
    }
}

思路2:写成模板形式,技巧在于i可以走一步,两步,走到第三步,也就是i - index >1 的时候,就要continue;substring 起点是index即可,那么substring就可以取1或者取2;

public class Solution {
    /*
     * @param : a string to be split
     * @return: all possible split string array
     */
    public List<List<String>> splitString(String s) {
        List<List<String>> lists = new ArrayList<List<String>>();
        if(s == null){
            return lists;
        }
        
        List<String> list = new ArrayList<String>();
        dfs(s, list, lists, 0);
        return lists;
    }
    
    private void dfs(String s, List<String> list, List<List<String>> lists, int index) {
        if(index == s.length()) {
            lists.add(new ArrayList<String>(list));
            return;
        }
        
        for(int i = index; i < s.length(); i++) {
            if(i - index > 1) {
                continue;
            }
            list.add(s.substring(index, i+1));//注意这里一定是i+1,否则substring(i,i)死循环;
            dfs(s, list, lists, i+1);
            list.remove(list.size() -1);
        }
    }
    
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值