标签:style blog color 使用 os io for div
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 = 0; 25 for( size_t i = 0; i != str.length(); ++i ) { 26 value = 10 * value + str[i] - ‘0‘; 27 } 28 if( value > 255 ) { return false; } 29 return true; 30 } 31 vector<string> address; 32 };
Restore IP Addresses,布布扣,bubuko.com
标签:style blog color 使用 os io for div
原文地址:http://www.cnblogs.com/moderate-fish/p/3920654.html