Given a string containing only digits, restore it by returning all possible valid IP address combinations.
Example:
Input: "25525511135"
Output: ["255.255.11.135", "255.255.111.35"]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/restore-ip-addresses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
三重遍历,每次把数字分成4段,即每次把“.” 放在不同位置。
class Solution {
List<String> ans = new ArrayList<>();
boolean checkValid (String s) {
if (s.length() > 3 || s.length() == 0) {
return false;
}
// 排除0开头的
if (s.length() > 1 && s.charAt(0) == '0') {
return false;
}
int nums = Integer.parseInt(s);
return (nums >= 0 && nums <= 255);
}
public List<String> restoreIpAddresses(String s) {
if (s.length() > 12) {
return ans;
}
for (int i = 0; i < s.length(); i++) {
for (int j = i + 1; j < s.length(); j++) {
for (int k = j + 1; k < s.length() ; k++) {
String ip1 = s.substring(0, i + 1);
String ip2 = s.substring(i + 1, j + 1);
String ip3 = s.substring(j + 1, k + 1);
String ip4 = s.substring(k + 1);
if (checkValid(ip1) && checkValid(ip2) && checkValid(ip3) && checkValid(ip4)) {
ans.add(ip1 + "." + ip2 + "." + ip3 + "." + ip4);
}
}
}
}
return ans;
}
}
本文介绍了一种解决LeetCode上复原IP地址问题的算法。通过三重遍历将字符串分割成四部分,每部分检查是否为有效的IP段。算法确保了分割后的IP地址的有效性和正确性。
1499

被折叠的 条评论
为什么被折叠?



