93. Restore IP Addresses 93.恢复IP地址
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
A valid IP address consists of exactly four integers (each integer is between 0 and 255) separated by single points.
Example:
Input: "25525511135"
Output: ["255.255.11.135", "255.255.111.35"]
原来的思路:
//这里不是从1开始的,是从start开始的,然后i最多等于start + 3.
//backtrace中,start递归换成i + 1
for (int sectionLength = 1; sectionLength < 4; sectionLength++) {
if (isValid())
}
应该有的思路:其实不用纠结什么字符串长度123,保证每一截都是有效的就行了。head这一截和剩下的部分。
控制remainingCount从4开始即可。
退出条件:s.length() == 0,不是s == ""
从1到最后一位,因为取head的时候需要包括在内
for (int i = 1; i <= s.length(); i++)
head是valid就回溯,不行就break
判断第一位是否等于0的方法:看看字符串长度和数字长度是否相等
s.length() == String.valueOf(val).length()
class Solution { //右边需要初始化 List<String> results = new ArrayList<>(); public List<String> restoreIpAddresses(String s) { //cc if (s.length() == 0) return results; backtrace(s, "", 4); return results; } public void backtrace(String s, String currentString, int remainingCount) { //exit if (s.length() == 0 && remainingCount == 0) { results.add(currentString.substring(0, currentString.length() - 1)); return ; } if (s.length() == 0 || remainingCount == 0) return ; for (int i = 1; i <= s.length(); i++) { String head = s.substring(0, i); if (isValid(head)) { backtrace(s.substring(i), currentString + head + ".", remainingCount - 1); }else break; } } private boolean isValid(String s) { int val = Integer.valueOf(s); if (val > 255) return false; return s.length() == String.valueOf(val).length(); } }