super easy java regex recursion solution


  • 0
    G

    public class Solution {
    public static List<String> restoreIpAddresses(String s) {
    List<String> as = new ArrayList<String>();
    if(s.length()>12)
    {
    return as;
    }
    StringBuilder sb = new StringBuilder(s);
    String regex ="([0-9]|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])(\.(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])){3}";
    int count=0;
    helper(as,sb,1,count,regex);
    return as;
    }

    public static void helper(List<String> as,StringBuilder sb,int start,int count,String regex)
    {
    	if(count==3 && !sb.toString().matches(regex))	
    	{		
    	     return;
    	}
    	if(count==3 && sb.toString().matches(regex)	)
    	{	
    		//System.out.println(as);
    		if(!as.contains(sb.toString()))
    		as.add(sb.toString());
    		return;
    	}
    	
    	for(int i=start; i<sb.length();i++)
    	{
    		
    		sb.insert(i, ".");		
    		count++;
    		helper(as,sb,i+2,count,regex);
    		sb.deleteCharAt(i);
    		count--;
    	}
    }
    

    }


Log in to reply
 

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