您的位置:首页 > 其它

2016.6.17——Valid Parentheses

2016-06-17 19:52 190 查看

Valid Parentheses

本题收获:

1.stack的使用

2.string和char的区别

  题目:  

  Given a string containing just the characters
'('
,
')'
,
'{'
,
'}'
,
'['
and
']'
, determine if the input string is valid.

  The brackets must close in the correct order,
"()"
and
"()[]{}"
are all valid but
"(]"
and
"([)]"
are not.

  注意题目中只是输入了一个字符串 如:“{}(]” 而不是{“{}[”,"[]"}

  思路:

  leetcode:用stack,括号为左边压入栈,右边的和栈顶对比,所有的都匹配返回true,不匹配返回false

  代码:

bool isValid(string s) {
stack<char> st;
for(char c : s){
if(c == '('|| c == '{' || c == '['){
st.push(c);
}else{
if(st.empty()) return false;
if(c == ')' && st.top() != '(') return false;
if(c == '}' && st.top() != '{') return false;
if(c == ']' && st.top() != '[') return false;
st.pop();
}
}
return st.empty();


  我的测试代码:

class MyClass
{
public:
bool isValid(string str)
{
stack<char> st;            //is <char> not<string>
for (size_t i = 0; i < str.size(); i++)
{
if (str[i] == '(' || str[i] == '{' || str[i] == '[')
{
st.push(str[i]);
}
else
{
if (str[i] == ')' && st.top() != '(') return false;
if (str[i] == ']' && st.top() != '[') return false;
if (str[i] == '}' && st.top() != '{') return false;                //不写st.pop()有什么差别
}
}
return true;                                                            //st.empty()
}
};


  完整代码:

// Valid Parentheses.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "iostream"
#include "stack"
#include "stack"
using namespace std;

class MyClass
{
public:
bool isValid(string str)
{
stack<char> st;            //is <char> not<string> 栈的定义,注意是string/char
for (size_t i = 0; i < str.size(); i++)
{
if (str[i] == '(' || str[i] == '{' || str[i] == '[')
{
st.push(str[i]);
}
else
{
if (str[i] == ')' && st.top() != '(') return false;
if (str[i] == ']' && st.top() != '[') return false;         //st.top(),有括号“,”栈的.后面都有()
if (str[i] == '}' && st.top() != '{') return false;                //不写st.pop()有什么差别
}
}
return true;                                                            //st.empty()
}
};
/*
class MyClass
{
public:
bool isValid(string str)
{
stack<char> st;            //is <char> not<string>
for (char c : str)
{
if (c == '(' || c == '{' || c == '[')
{
st.push(c);
}
else
{
if (c == ')' && st.top() != '(') return false;
if (c == ']' && st.top() != '[') return false;
if (c == '}' && st.top() != '{') return false;
st.pop();
}
}
return st.empty();
}

};*/

int _tmain(int argc, _TCHAR* argv[])
{
string str = "({[]})";
int m = 0;
MyClass solution;
m = solution.isValid(str);
cout << m << endl;
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: