File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed
solution/0093.Restore IP Addresses Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ private:
3+ inline string Check (string &s, int widths[])
4+ {
5+ widths[1 ] += widths[0 ] ;
6+ widths[2 ] += widths[1 ] ;
7+ widths[3 ] = s.length () - widths[2 ] ;
8+
9+ if (widths[3 ] < 1 || widths[3 ] > 3 )
10+ return " " ;
11+
12+ widths[3 ] = s.length () ;
13+
14+ for (int seg = 0 ; seg < 4 ; ++seg)
15+ {
16+ int num = 0 ;
17+ for (int i = (seg == 0 ? 0 : widths[seg-1 ]); i < widths[seg]; ++i)
18+ {
19+ num *= 10 ;
20+ num += s[i] - ' 0' ;
21+ }
22+ if (num > 255 )
23+ return " " ;
24+
25+ int w = widths[seg] - (seg == 0 ? 0 : widths[seg-1 ]) ;
26+ if (w == 3 && num < 100 )
27+ return " " ;
28+ if (w == 2 && num < 10 )
29+ return " " ;
30+ }
31+ string res = s ;
32+ for (int i = 2 ; i >= 0 ; --i)
33+ res.insert (widths[i], " ." ) ;
34+
35+ return res ;
36+ }
37+ public:
38+ vector<string> restoreIpAddresses (string s) {
39+ int widths[4 ] ;
40+ vector<string> res ;
41+ for (int i = 0 ; i < 27 ; ++i)
42+ {
43+ widths[0 ] = 1 + i%3 ;
44+ widths[1 ] = 1 + i/3 %3 ;
45+ widths[2 ] = 1 + i/9 ;
46+
47+ string tmp = Check (s, widths) ;
48+ if (tmp.size () != 0 )
49+ res.push_back (tmp) ;
50+ }
51+
52+ return res;
53+ }
54+ };
You can’t perform that action at this time.
0 commit comments