93. Restore IP Addresses

93. Restore IP Addresses

Given a string containing only digits, restore it by returning all possible valid IP address combinations.

For example:
Given "25525511135",

return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)

 
Hide Tags
 Backtracking String
 
public class Solution {
  public List<String> restoreIpAddresses(String s) {
    List<String> results = new ArrayList<String>();
    restoreIpAddresses(results, s, 0, 0, new LinkedList<String>());
    return results;
  }

  private void restoreIpAddresses(List<String> results, String s, int from, int count, Deque<String> current) {
    if (count == 4) {
      if (from == s.length()) { //at the end of string
        StringBuilder sb = new StringBuilder();
        for (String currentNum : current) {
          sb.append(currentNum);
          sb.append(".");
        }
        sb.setLength(sb.length() - 1);
        results.add(sb.toString());
      }
      return;
    }

    for (int len = 1; len <= 3; ++len) {
      int end = from + len;
      if(end>s.length())
        return;
      String num = s.substring(from, end);
      boolean valid = isValid(num);
      if (!valid)
        continue;
      current.add(num);
      restoreIpAddresses(results, s, from + len, count + 1, current);
      current.removeLast();
    }
  }

  private boolean isValid(String s) {
    if (s.length() > 3 || s.length() == 0 ||
      (s.charAt(0) == '0' && s.length() > 1) ||
      Integer.parseInt(s) > 255)
      return false;
    return true;
  }
}

 

 
posted @ 2016-07-25 08:03  新一代的天皇巨星  阅读(142)  评论(0编辑  收藏  举报