Standard DFS Java Solution


  • 0
    Z
    public class Solution {
        public List<List<String>> partition(String s) {
            List<List<String>> result= new ArrayList<>();
            dfs(s,new ArrayList<String>(),result);
            return result;
        }
        
        public void dfs(String s,List<String> path,List<List<String>> result){
           if(s.length()==0){
               result.add(path);
               return;
           }
            for(int i=1;i<=s.length();i++){
                String s1=s.substring(0,i);
                if(isPal(s1)){
                    List<String> nPath= new ArrayList<>(path);
                    nPath.add(s1);
                    dfs(s.substring(i),nPath,result);
                }
            }
        }
        
        public boolean isPal(String s){
            int start=0;
            int end=s.length()-1;
            while(start<end){
                if(s.charAt(start++)!=s.charAt(end--))
                return false;
            }
            return true;
        }
        
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.