/*
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)
*/
/*
如果长度为12,只能是3个3个切割
*/
func restoreIpAddresses(_ ipString: String) -> [String] {
func isValid(_ subIp: String) -> Bool {
//长度限制
let length = subIp.lengthOfBytes(using: .ascii)
guard length <= 3, length > 0 else {
return false
}
//第一个字符为0,但整体长度>1
if subIp.characters.first == "0", length > 1 {
return false
}
//数值超过255
if let value = Int(subIp) {
if (value > 255) {
return false
}
} else {
return false
}
return true
}
let length = ipString.lengthOfBytes(using: .ascii)
guard length >= 4 else {
return []
}
var retStringArray: [String] = []
var startIndex = ipString.startIndex
var endIndex = ipString.endIndex
//i,j,k 标识每次选择结束的 index,一旦前面的选择完,最后一个就可以确定,
//中途每一次选择,如果 index 超过了 length,则直接退出
for i in 0 ..< 3 {
func canDealSection(_ start: Int, _ end: Int) -> (Bool, String) {
if end >= (length - 1) {
return (false, "")
}
let tldEndIndex = ipString.index(ipString.startIndex, offsetBy: end+1)
let tldStartIndex = ipString.index(ipString.startIndex, offsetBy: start)
let range = Range(uncheckedBounds: (lower: tldStartIndex, upper: tldEndIndex))
let section = ipString.substring(with: range)
if isValid(section) {
return (true, section)
} else {
return (false, "")
}
}
var section1 = ""
let (status, value) = canDealSection(0, i)
if !status {
break
}
section1 = value
print("section1 is \(section1)")
for j in i + 1 ..< i + 4 {
var section2 = ""
let (status, value) = canDealSection(i+1, j)
if !status {
break
}
section2 = value
print("section2 is \(section2)")
for k in j + 1 ..< j + 4 {
var section3 = ""
let (status, value) = canDealSection(j+1, k)
if !status {
break
}
section3 = value
print("section3 is \(section3)")
//最后一个section,由剩余长度决定
let index = ipString.index(ipString.startIndex, offsetBy: k + 1)
let section4 = ipString.substring(from: index)
print("section4 is \(section4)")
if isValid(section4) {
var validIpString = ""
validIpString.append(section1)
validIpString.append(".")
validIpString.append(section2)
validIpString.append(".")
validIpString.append(section3)
validIpString.append(".")
validIpString.append(section4)
retStringArray.append(validIpString)
print("----- \(validIpString) -----")
}
}
}
}
return retStringArray
}
93. Restore IP Addresses
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- LeetCode 93 Restore IP Addresses Given a string containin...
- Given a string containing only digits, restore it by retu...
- Given a string containing only digits, restore it by retu...
- NAIVE 解法,O(n3): dfs dfs解法我写了一个,我想的是类似Combination Sum那种的;但...
- Given a string containing only digits, restore it by retu...