File tree Expand file tree Collapse file tree 1 file changed +71
-0
lines changed Expand file tree Collapse file tree 1 file changed +71
-0
lines changed Original file line number Diff line number Diff line change 1+ // Probably bigger than it needs to be, but I'm feeling lazy !
2+ // Performance is also perfect so :shrug:
3+
4+ class Solution {
5+ public:
6+ bool checkValidString (string s) {
7+ return checkForward (s) && checkBack (s);
8+ }
9+
10+ bool checkForward (string s) {
11+ int opened = 0 ;
12+ int wildcards = 0 ;
13+
14+ for (string::iterator it = s.begin (); it != s.end (); ++it) {
15+ if (*it == ' (' ) {
16+ ++opened;
17+ }
18+ else if (*it == ' )' ) {
19+ --opened;
20+
21+ while (opened < 0 && wildcards > 0 ) {
22+ ++opened;
23+ --wildcards;
24+ }
25+
26+ if (opened < 0 ) {
27+ return false ;
28+ }
29+ } else if (*it == ' *' ) {
30+ ++wildcards;
31+ }
32+ }
33+
34+ if (opened == 0 || abs (opened) <= wildcards) {
35+ return true ;
36+ }
37+
38+ return false ;
39+ }
40+
41+ bool checkBack (string s) {
42+ int closed = 0 ;
43+ int wildcards = 0 ;
44+
45+ for (string::reverse_iterator it = s.rbegin (); it != s.rend (); ++it) {
46+ if (*it == ' )' ) {
47+ ++closed;
48+ }
49+ else if (*it == ' (' ) {
50+ --closed;
51+
52+ while (closed < 0 && wildcards > 0 ) {
53+ ++closed;
54+ --wildcards;
55+ }
56+
57+ if (closed < 0 ) {
58+ return false ;
59+ }
60+ } else if (*it == ' *' ) {
61+ ++wildcards;
62+ }
63+ }
64+
65+ if (closed == 0 || abs (closed) <= wildcards) {
66+ return true ;
67+ }
68+
69+ return false ;
70+ }
71+ };
You can’t perform that action at this time.
0 commit comments