LeetCode-有效括号

  这道题,第一想法是把三种括号组对儿存入哈希表中,然后遍历字符串遇到key就搜索最近的value,若找不到就退出,找到就配对成功。配对成功后,把两个值都改为空格,最后只要遍历字符串中有没有非空格的字符,就可以知道true还是false。哈希表不太熟所以用循环写了一下:

	#include "iostream"
	#include "string"
	#include "map"
	using namespace std;
	class Solution {
	public:
	bool isValid(string s) {

    	if(s[0]==')' || s[0]==']' || s[0]=='}') return false;

    	int j;
    	for(int i=0;i<s.length();i++)
    	{
    	    if(s[i]=='(')
    	    {
    	        if(s.find(")",i)==-1) return false;
    	        else
    	        {
    	            j=s.find(")",i);
    	            s[i]=' ';
    	            s[j]=' ';
    	        }
    	    }
    	    if(s[i]=='[')
	        {
	            if(s.find("]",i)==-1) return false;
	            else
	            {
	                j=s.find("]",i);
	                s[i]=' ';
	                s[j]=' ';
	            }
	        }
	        if(s[i]=='{')
	        {
	            if(s.find("}",i)==-1) return false;
	            else
	            {
	                j=s.find("}",i);
	                s[i]=' ';
	                s[j]=' ';
	            }
	        }
	    }
	    for(int k=0;k<s.length();k++)
	    {
	        if(s[k]!=' ')
	        return false;
	    }
	    return true;
	}
};

Wrong Answer 73/76 cases passed (N/A)

Testcase “([)]”

Answer true

Expected Answer false

  提交后发现,有四个测试用例没有通过,原因是,这样修改字符,就无法检测到做括号时候按正常顺序闭合,如测试用例"([)]",第一次修改完字符串为" [ ]",这样就不正确了。

  这道题更好的思路是使用栈来解决,非常巧妙。在题解及基础上做了一些优化改进。

  76/76 cases passed (0 ms)

  Your runtime beats 100 % of cpp submissions

  Your memory usage beats 100 % of cpp submissions (8 MB)

#include "iostream"
#include "string"
#include "map"
#include "stack"
using namespace std;
	class Solution{
	public:
	bool isValid(string s) {

	if(s[0]==')' || s[0]==']' || s[0]=='}') return false;
	if(s.length()%2!=0) return false;

	map<char,char>m;
	m.insert(make_pair(')','('));
	m.insert(make_pair(']','['));
	m.insert(make_pair('}','{'));
	// m.insert(map<char,char>::value_type(')','('));
	// m.insert(map<char,char>::value_type(']','['));
	// m.insert(map<char,char>::value_type('}','{'));

	stack<char>st;

	for(int i=0;i<s.length();i++)
	{
		if(s[i]=='(' || s[i]=='[' || s[i]=='{' )
	    {
		    st.push(s[i]);
	    }
		else if(s[i]==')' || s[i]==']' || s[i]=='}' )
		{
		    if(st.empty()) return false;
		    if(m[s[i]]==st.top())
		    {
			    st.pop();
			    continue;
		    }
		    else
		    {
			    return false;
		    }

		}
	
		}
		if(st.empty()) return true;
		else
		return false;
	
	}
};

  使用哈希表时候有一个需要注意,是用闭括号来寻找开括号配对,在存入哈希表时候要注意顺序!

发布了36 篇原创文章 · 获赞 0 · 访问量 600

猜你喜欢

转载自blog.csdn.net/weixin_43199933/article/details/104933630