首页 > 其他 > 详细

93. Restore IP Addresses

时间:2016-07-25 08:08:53      阅读:254      评论:0      收藏:0      [点我收藏+]

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;
  }
}

 

 

93. Restore IP Addresses

原文:http://www.cnblogs.com/neweracoding/p/5702217.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!