关于leetcode中c++ STL 的几道题

1. Valid Parentheses

用来判断字符串中的括号是否合法的一道题。注意输入只会有 (, ) , {, }, [, ]这么几种情况。

合法的括号是以一定的顺序进行匹配的一些。比如:"()[]’, 或者"([])"等,而以"([)]"这种为类型的表示是有错误的。

很显然用“stack”来作为数据结构来实现这道题,每一次插入一个元素的时候都进行匹配,,如果匹配成功了,那么就将栈顶元素出栈,继续下一个元素,

否则直接将这个元素入栈。最后判断栈是否为空。

整个代码的实现如下,可能不是很简洁,但是思路很清晰:

/*————————–valid parentheses————————————————–*///用stack来实现。//By Lingtao 2015/04/20#include <stack>#include <vector>bool isValid(string s){if (s.size() % 2 != 0)return false;if (s.empty())return true;stack<char>st;char top;for (string::iterator iter = s.begin();iter != s.end(); iter++){if (st.empty()){st.push(*iter);continue;}top = st.top();switch (top){case'(':if (*iter == ')')st.pop();elsest.push(*iter);break;case'[':if (*iter == ']')st.pop();elsest.push(*iter);break;case'{':if (*iter == '}')st.pop();elsest.push(*iter);break;default:return false;break;}}if (st.empty())return true;elsereturn false;}

未完待续。

旅游,放松心情,用眼睛享受风景。

关于leetcode中c++ STL 的几道题

相关文章:

你感兴趣的文章:

标签云: