首页 > 代码库 > Restore IP Addresses
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)
思路:直接使用DFS即可。
1 class Solution { 2 public: 3 vector<string> restoreIpAddresses( string s ) { 4 string ip; 5 ProcessSub( ip, 0, s ); 6 return address; 7 } 8 private: 9 void ProcessSub( string ip, int step, string str ) {10 if( step == 4 ) { address.push_back( ip ); return; }11 int sLen = str.length();12 if( sLen < 4-step || sLen > 3*(4-step) ) { return; }13 for( int i = max( 1, sLen-3*(3-step) ); i <= min( 3, sLen-(3-step) ); ++i ) {14 string subStr = str.substr( 0, i );15 if( IsLegal( subStr ) ) {16 if( !ip.empty() ) { subStr = ip + "." + subStr; }17 ProcessSub( subStr, step+1, str.substr( i ) );18 }19 }20 }21 bool IsLegal( const string& str ) {22 if( str.length() == 1 ) { return true; }23 if( str[0] == ‘0‘ ) { return false; }24 int value = http://www.mamicode.com/0;25 for( size_t i = 0; i != str.length(); ++i ) {26 value = http://www.mamicode.com/10 * value + str[i] - ‘0‘;27 }28 if( value > 255 ) { return false; }29 return true;30 }31 vector<string> address;32 };
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。