LeetCode Restore IP Addresses
Posted 我本善良
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode Restore IP Addresses相关的知识,希望对你有一定的参考价值。
DFS
class Solution { public: vector<string> restoreIpAddresses(string s) { return insertDot(s, 0, 3); } vector<string> insertDot(string s, int beginIndex, int countOfDot /*3, 2, 1, 0*/) { vector<string> result; if( (s.size() - beginIndex) < (countOfDot + 1) || (s.size() - beginIndex - 1) > (countOfDot +1) * 3) return result; if(countOfDot == 0) { string partition = s.substr(beginIndex); if(partition.size() > 1 && partition[0] == ‘0‘) //Error 4: if the first char is 0, then no more chars, such as 1.00.1.1 is no valid; { return result; } int val = std::stoi(partition); if(val >= 0 && val <256) { result.push_back(partition); } return result; } for(int i = beginIndex + 1; i< s.size();i++ ) //Error 1: i< s.size() -1 { string partition = s.substr(beginIndex, i - beginIndex); if(partition.size() > 1 && partition[0] == ‘0‘) //Error 3: if the first char is 0, then no more chars, such as 1.00.1.1 is no valid; { break; } int val = std::stoi(partition); if(val > 255) break; if(val >= 0 && val <256) { vector<string> subresult = insertDot(s, i, countOfDot - 1); if(subresult.size() != 0) { for(int j = 0; j< subresult.size(); j++) //Error 2: j< s.size() -1 { string onepartition = partition + "." + subresult[j]; result.push_back(onepartition); } } } } return result; } };
以上是关于LeetCode Restore IP Addresses的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] Restore IP Addresses 复原IP地址
[Leetcode] restore ip address 存储IP地址
[LeetCode] Restore IP Addresses 复原IP地址