LintCode 分割字符串

来源:互联网 发布:源码数据库放在哪里 编辑:程序博客网 时间:2024/05/29 02:05

给一个字符串,你可以选择在一个字符或两个相邻字符之后拆分字符串,使字符串由仅一个字符或两个字符组成,输出所有可能的结果

给一个字符串”123”
返回[[“1”,”2”,”3”],[“12”,”3”],[“1”,”23”]]

递归,和LintCode 电话号码的字母组合类似。
代码如下:

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>> result=new ArrayList<List<String>>();//全部结果        List<String> tempResult=new ArrayList<String>();//符合要求的某一个分割结果        recursion(s,0,tempResult,result);        return result;    }    public  void recursion(String s,int count,List<String> tempResult,List<List<String>> result) {        if(count>=s.length()) {//count用来记录tempResult中的字符数,或者说处理到了第几个字符            if(count==s.length()) {//如果等于原字符串长度,就加到全部结果中                result.add(new ArrayList<String>(tempResult));            }            return;        }        for(int i=1;i<=2;i++) {//对每个字符s[i]来说,可以单独把s[i]存入tempResult,或者把s[i]和s[i+1]放在一起存入tempResult;            if(count+i<=s.length()) {//如果没超过原字符串长度,就把这个分割部分加入tempResult                tempResult.add(s.substring(count, count+i));            }            recursion(s,count+i,tempResult,result); //然后递归处理后面的字符。              if(count+i<=s.length()) {//如果刚刚加入了某个分割部分,返回时要把刚刚加入的部分删掉。                tempResult.remove(tempResult.size()-1);            }        }           }}
原创粉丝点击