lintcode-medium-Restore IP Addresses
Posted 哥布林工程师
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lintcode-medium-Restore IP Addresses相关的知识,希望对你有一定的参考价值。
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
Example
Given "25525511135"
, return
[
"255.255.11.135",
"255.255.111.35"
]
Order does not matter.
public class Solution { /** * @param s the IP string * @return All possible valid IP addresses */ public ArrayList<String> restoreIpAddresses(String s) { // Write your code here ArrayList<String> result = new ArrayList<String>(); String line = ""; helper(result, line, 0, s, 0); return result; } public void helper(ArrayList<String> result, String line, int start, String s, int count){ if(count == 4){ if(start == s.length()){ line = line.substring(0, line.length() - 1); result.add(line); return; } else return; } for(int i = start + 1; i <= start + 3 && i <= s.length(); i++){ if(valid(s.substring(start, i))){ String new_line = line + s.substring(start, i) + "."; helper(result, new_line, i, s, count + 1); } } return; } public boolean valid(String s){ if(s.charAt(0) == ‘0‘ && s.length() > 1) return false; int temp = Integer.parseInt(s); return (temp >= 0 && temp <= 255); } }
以上是关于lintcode-medium-Restore IP Addresses的主要内容,如果未能解决你的问题,请参考以下文章