力扣(LeetCode)试题20-有效的括号 C++代码
时间:2020-07-01 12:29:34
收藏:0
阅读:375
可能是代码不规范,在力扣端编译环境下出错:Line 35: Char 10: runtime error: load of value 64, which is not a valid value for type ‘bool‘ (solution.cpp)。
在VS环境下没有问题。先搁置问题,以后再来改善。
1 #include <iostream>
2 #include <string>
3
4 using namespace std;
5
6 class Solution
7 {
8 public:
9 bool isValid(string s)
10 {
11 bool flag;
12 if (s.length() % 2 != 0)
13 flag = 0;
14 if (s.length() == 0)
15 flag = 1;
16 else
17 {
18 int s_m = s.length() / 2;
19 int k = s.length();
20 for (int i = 0; i < s_m; i++)
21 {
22 k -= 1;
23 if ((s[i] == ‘(‘ && s[k] == ‘)‘) || ((s[i] == ‘[‘ && s[k] == ‘]‘))
24 || ((s[i] == ‘{‘ && s[k] == ‘}‘)))
25 {
26 flag = 1;
27 }
28 else
29 {
30 for (int j = 0; j < s.length(); j = j + 2)
31 {
32 if ((s[j] == ‘(‘ && s[j + 1] == ‘)‘) || ((s[j] == ‘[‘ && s[j + 1] == ‘]‘))
33 || ((s[j] == ‘{‘ && s[j + 1] == ‘}‘)))
34 flag = 1;
35 else
36 flag = 0;
37 }
38 }
39
40 }
41 }
42 return flag;
43 }
44 };
45
46 int main(){
47 bool result;
48 Solution sol;
49 string str = "{[]}";
50 result = sol.isValid(str);
51 cout << result << endl;
52 int y;
53 cin >> y;
54 return 0;
55 }
评论(0)