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.
【My Solution:】
#include "stdafx.h" #include <iostream> #include <vector> using namespace std; class Solution { public: bool checkMatch(char first,char second){ bool isMatch = false; if((first == ‘(‘ && second == ‘)‘) || (first == ‘[‘ && second == ‘]‘) || (first == ‘{‘ && second == ‘}‘)) { isMatch = true; } return isMatch; } bool isValid(string s) { bool isValid = false; vector<char> vTemp; if(s.length() <= 0){ return isValid; } //vTemp.push_back(s[0]); for(int i = 0; i < s.length(); i++){ if(vTemp.size() == 0){ vTemp.push_back(s[i]); }else{ vector<char>::iterator id = vTemp.end()-1; if(checkMatch((*id),s[i])){ vTemp.erase(id); }else{ vTemp.push_back(s[i]); } } } if(vTemp.size() == 0){ isValid = true; } return isValid; } }; int main(){ Solution solution; solution.isValid("()"); solution.isValid("()[]{}"); solution.isValid("([)]"); return 0; }
【other‘s】算法使用相同,都使用栈来实现,但his更简洁,1、直接用到了已有的数据结构stack;2、匹配用到了ASCII码,但这样不合适,万一输入为“sdsf”等字符,则结果不正确。
public class Solution { public boolean isValid(String s) { char [] arr = s.toCharArray(); Stack stack = new Stack(); for(char ch : arr){ if(stack.isEmpty()){ stack.push(ch); }else{ char top = (char)stack.lastElement(); if(ch - top == 1 || ch - top == 2){ stack.pop(); }else{ stack.push(ch); } } } if(stack.isEmpty()){ return true; } return false; }
时间: 2024-12-23 20:00:08