Restore IP Addresses
来源:互联网 发布:java super.m = 10 编辑:程序博客网 时间:2024/06/18 14:21
-----QUESTION-----
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)
-----SOLUTION-----
class Solution {public: vector<string> restoreIpAddresses(string s) { result.clear(); dfs(s, 0, 0); return result; } void dfs(string s, int startPos, int depth) { if (depth ==3) { string str = s.substr(startPos,s.length()-startPos); int restStrLen = str.length(); int n = atoi(str.c_str()); if(n>255) return; if(restStrLen > 1 && s[startPos]=='0') return; result.push_back(s); } else { string str = s.substr(startPos,s.length()-startPos); int restStrLen = str.length(); if(restStrLen>=4-depth) { str = s.substr(0,startPos+1)+"."+s.substr(startPos+1,restStrLen-1); dfs(str, startPos+2, depth+1); if(s[startPos] == '0') return; } if(restStrLen>=5-depth) { str = s.substr(0,startPos+2) +"."+s.substr(startPos+2,restStrLen-2); dfs(str, startPos+3, depth+1); } if(restStrLen>=6-depth) { str = s.substr(startPos,3); int n = atoi(str.c_str()); if(n>255) return; str = s.substr(0,startPos+3)+"."+s.substr(startPos+3,restStrLen-3); dfs(str, startPos+4, depth+1); } } }private: vector<string> result;};
0 0
- LeetCode: Restore IP Addresses
- Restore IP Addresses
- LeetCode : Restore IP Addresses
- [LeetCode] Restore IP Addresses
- Restore IP Addresses
- [LeetCode]Restore IP Addresses
- Restore IP Addresses
- Restore IP Addresses
- LeetCode:Restore IP Addresses
- Restore IP Addresses
- Restore IP Addresses
- LeetCode Restore IP Addresses
- [leetcode] Restore IP Addresses
- Restore IP Addresses
- LeetCode:Restore IP Addresses
- [LeetCode] Restore IP Addresses
- LeetCode - Restore IP Addresses
- LeetCode | Restore IP Addresses
- JMeter使用记录3 -- 性能监控插件jmeter-plugins
- 使用框架的php如果使用定时服务Cronjob
- 深入Pthread(五):线程属性
- UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)
- HDUJ 1203 I NEED A OFFER!
- Restore IP Addresses
- 深入Pthread(四):一次初始化-pthread_once_t
- HDU 题目1051 Wooden Sticks
- string和NSString*的相互转化
- handler自定义使用
- unresolved external symbol _WinMain@16 referenced in function ___tmainCRTSta
- 记我的第一份工作
- Extjs4之下拉框三级联动
- 深入Phtread(三):线程的同步-Condition Variables