JAVA backtracking solution


  • 0

    ...

    public List<String> restoreIpAddresses(String s) {
        List<String> ans = new ArrayList<>();
        
        if (s != null && s.length() > 0) {
            solve(ans, s, 0, new StringBuilder(), 0);
        }
        
        return ans;
    }
    
    private void solve(List<String> ans, String s, int index, StringBuilder cur, int pointCnt) {
        if (index == s.length() && pointCnt == 4) {
            ans.add(cur.substring(0, cur.length()-1));
        } else if (index < s.length() && pointCnt < 4) {
            solve(ans, s, index+1, new StringBuilder(cur).append(s.charAt(index)).append("."), pointCnt+1);
            
            if (index+1 < s.length() && s.charAt(index) != '0') {
                solve(ans, s, index+2, new StringBuilder(cur).append(s, index, index+2).append("."), pointCnt+1);
                
                if (index+2 < s.length() && s.substring(index, index+3).compareTo("255") <=0) {
                    solve(ans, s, index+3, new StringBuilder(cur).append(s, index, index+3).append("."), pointCnt+1);
                }
            }
        }
    }

Log in to reply
 

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