-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparens.cpp
More file actions
61 lines (57 loc) · 1.27 KB
/
Copy pathparens.cpp
File metadata and controls
61 lines (57 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
int balanced( const char *str )
{
int opens = 0;
int idx = 0;
int last_open_idx = 0;
bool found_paren = false;
while( *str != '\0' )
{
if( *str == '(' )
{
++opens;
found_paren = true;
last_open_idx = idx;
}
else if( *str == ')' )
{
--opens;
if( opens < 0 ) return idx;
found_paren = true;
}
++idx;
++str;
}
if( found_paren == false ) return -2;
if( opens > 0 ) return last_open_idx;
return -1;
}
void test( const char *str )
{
int result = balanced( str );
std::cout << "\"" << str << "\"";
if( result == -1 )
{
std::cout << " has balanced parentheses." << std::endl;
}
else
{
if( result == -2 )
{
std::cout << " does not have parentheses." << std::endl;
}
else
{
std::cout << " has unbalanced parentheses. Index: " << result << std::endl;
}
}
}
int main( int argv, char *argc[] )
{
const char *test_string_1 = "((())())()";
const char *test_string_2 = ")()(";
const char *test_string_3 = "())";
test( test_string_1 );
test( test_string_2 );
test( test_string_3 );
}