给出一个仅包含字符'(',')','{','}','['和']',的字符串,判断给出的字符串是否是合法的括号序列
括号必须以正确的顺序关闭,"()"和"()[]{}"都是合法的括号序列,但"(]"和"([)]"不合法。
括号必须以正确的顺序关闭,"()"和"()[]{}"都是合法的括号序列,但"(]"和"([)]"不合法。
数据范围:字符串长度
要求:空间复杂度 ,时间复杂度
import java.util.*; public class Solution { public boolean isValid (String s) { // 使用栈来跟踪最近的开括号 Stack<Character> stack = new Stack<>(); // 遍历字符串中的每个字符 for (char c : s.toCharArray()) { // 如果是开括号,压入栈中 if (c == '(' || c == '[' || c == '{') { stack.push(c); } else if (c == ')' || c == ']' || c == '}') { // 如果是闭括号,检查栈是否为空或栈顶元素是否匹配 if (stack.isEmpty() || !isMatchingPair(stack.peek(), c)) { return false; } // 如果匹配,弹出栈顶元素 stack.pop(); } } // 如果栈为空,则所有括号都正确匹配 return stack.isEmpty(); } // 检查两个字符是否是匹配的括号对 private static boolean isMatchingPair(char open, char close) { return (open == '(' && close == ')') || (open == '[' && close == ']') || (open == '{' && close == '}'); } }
public class Solution { private Character pair(Character c) { switch(c) { case ')': return '('; case ']': return '['; case '}': return '{'; default: return null; } } public boolean isValid (String s) { Stack<Character> stack = new Stack<>(); Character c; for (int i=0; i<s.length(); i++) { c = s.charAt(i); if (c == '(' || c == '[' || c == '{') { stack.push(c); } else { if (!stack.empty() && pair(c) == stack.peek()) { stack.pop(); } else { return false; } } } if (!stack.empty()) { return false; } return true; } }
public class Solution { public boolean isValid (String s) { if (s.length() % 2 != 0) return false; char[] arr = s.toCharArray(); Deque<Character> stack = new ArrayDeque<>(); for (int i = 0; i < arr.length; i++) { if (arr[i] == '(' || arr[i] == '[' || arr[i] == '{') { stack.push(arr[i]); } else if (!stack.isEmpty()) { if (arr[i] == ')') { if (stack.peek() == '(') stack.pop(); else return false; } else if (arr[i] == ']') { if (stack.peek() == '[') stack.pop(); else return false; } else if (arr[i] == '}') { if (stack.peek() == '{') stack.pop(); else return false; } else return false; } } return stack.isEmpty(); } }
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return bool布尔型 */ public boolean isValid (String s) { // write code here // 1.创建一个栈,用来匹配左右括号 Stack<Character> stack = new Stack<>(); // 2.遍历字符串 for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == '(' || c == '{' || c == '[') { // 如果是左括号,直接入栈 stack.push(c); } else if (c == ')') { // 如果是')',则观察栈顶元素,若是'('则出栈 if (!stack.isEmpty() && stack.peek() == '(') { stack.pop(); } else { return false; } } else if (c == '}') { // 如果是'}',则观察栈顶元素,若是'{'则出栈 if (!stack.isEmpty() && stack.peek() == '{') { stack.pop(); } else { return false; } } else if (c == ']') { // 如果是']',则观察栈顶元素,若是'['则出栈 if (!stack.isEmpty() && stack.peek() == '[') { stack.pop(); } else { return false; } } } // 3.若栈空,则有效 return stack.isEmpty(); } }
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return bool布尔型 */ public boolean isValid (String s) { // write code here String[] split = s.split(","); int length = split.length; if (length == 1 ) { return false; } else { if (length % 2 != 0) { return false; } else { boolean flag = true; int i = 0; while (flag) { if (split[i] == "(") { if (split[i + 1] == ")") { flag = true; } else flag = false; } else if (split[i] == "[") { if (split[i + 1] == "]") { flag = true; } else flag = false; } else if (split[i] == "{") { if (split[i + 1] == "}") { flag = true; } else flag = false; } else flag = false; } return flag; } } } }
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return bool布尔型 */ public boolean isValid (String s) { Deque<Character> deque = new ArrayDeque<Character>(); // s = s.substring(1, s.length() - 1); System.out.println(s); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == '(' || c == '[' || c == '{') { deque.push(c); } else { if (deque.size() == 0) { return false; } char c1 = deque.pop(); String str = c1 + "" + c; if (!(str.equals("()") || str.equals("[]") || str.equals("{}"))) { return false; } } } return deque.size() == 0 ? true : false; } }
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return bool布尔型 */ public boolean isValid (String s) { // write code here Map<Character, Character> map = new HashMap<>(); map.put(')', '('); map.put(']', '['); map.put('}', '{'); Stack<Character> signs = new Stack<>(); for (int i = 0; i < s.length(); i++) { if (signs.empty() || map.values().contains(s.charAt(i))) { // open sign signs.push(s.charAt(i)); } else { // close sign if (signs.peek() == map.get(s.charAt(i))) { signs.pop(); } } } return signs.empty() ? true : false; } }
import java.util.*; public class Solution { class AAAA { char c; AAAA next; AAAA pri; public AAAA (char c) { this.c = c; } } AAAA quene; /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return bool布尔型 */ public boolean isValid (String s) { // write code here int lenght = s.length(); quene = new AAAA('0'); for (int i = 0; i < lenght ; i++) { char c = s.charAt(i); if (c == '(' || c == '[' || c == '{') { // 入栈 addAAAA(c); // 出栈并检查 } else if (quene.c == '0' || !check(c)) { return false; } } return quene.c == '0'; } public boolean check (char c) { // ')' - '(' == 1; // ']' - '[' == 2; // '}' - '{' == 2 char a = outAAAA(); return (c - a < 3) && (c - a > 0); } public boolean addAAAA (char c) { AAAA q = new AAAA(c); q.pri = quene; quene.next = q; quene = q; return true; } // 出栈 public char outAAAA() { char c = quene.c; AAAA q = quene.pri; quene.pri = null; quene = q; quene.next = null; return c; } }
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return bool布尔型 */ public boolean isValid (String s) { // write code here Stack<Character> s1 = new Stack<Character>(); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '{' || s.charAt(i) == '[' || s.charAt(i) == '(') { s1.push(s.charAt(i)); } else { if (!s1.isEmpty() && isMatch(s1.peek(), s.charAt(i))) { s1.pop(); } else { return false; } } } if (s1.isEmpty()) return true; return false; } public boolean isMatch (char s1, char s2) { switch (s1) { case '{': return '}' == s2 ? true : false; case '[': return ']' == s2 ? true : false; case '(': return ')' == s2 ? true : false; } return false; } }
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return bool布尔型 */ public boolean isValid (String s) { // write code here if (s.length() == 0 || s.length() % 2 == 1) { return false; } if (s.charAt(0) == ')' || s.charAt(0) == '}' || s.charAt(0) == ']') { return false; } Stack<Character> stack = new Stack<>(); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '(' || s.charAt(i) == '{' || s.charAt(i) == '[') { stack.push(s.charAt(i)); } else { Character pop = stack.pop(); if (s.charAt(i) == ')' && pop != '(') { return false; } if (s.charAt(i) == '}' && pop != '{') { return false; } if (s.charAt(i) == ']' && pop != '[') { return false; } } } return stack.size() == 0; } }
public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return bool布尔型 */ public static boolean isValid (String s) { // write code here if ((s.length() % 2) != 0) { return false; } int i = 0; StringBuilder sb = new StringBuilder(s); while (s.length() >= 2) { if ((s.charAt(i) == '(') && (s.charAt(i + 1) == ')')) { sb.delete(i, i + 2); s = sb.toString(); i = 0; continue; } if ((s.charAt(i) == '[') && (s.charAt(i + 1) == ']')) { sb.delete(i, i + 2); s = sb.toString(); i = 0; continue; } if ((s.charAt(i) == '{') && (s.charAt(i + 1) == '}')) { sb.delete(i, i + 2); s = sb.toString(); i = 0; continue; } i++; if (i == s.length() - 1) { return false; } } return true; } }
public boolean isValid (String s) { Stack<Character> st=new Stack<>(); for(int i=0;i<s.length();i++){ if(s.charAt(i)=='('){ st.push(')'); }else if(s.charAt(i)=='['){ st.push(']'); }else if(s.charAt(i)=='{'){ st.push('}'); }else{ //不是增加元素,是要弹出,但st为空,那就false if(st.isEmpty()){ return false; } if(st.pop()!=s.charAt(i)){ return false; } } } if(!st.isEmpty()){ return false; } return true; }
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return bool布尔型 */ public boolean isValid (String s) { // write code here if(s == null || s.length() == 0) { return true; } int len = s.length(); if(len % 2 != 0) { return false; } char[] chs = s.toCharArray(); Stack<Character> sta = new Stack<>(); for(int i = 0; i < chs.length; i++) { if(chs[i] == '(' || chs[i] == '{' || chs[i] == '[') { sta.push(chs[i]); } else if(sta.isEmpty()) { return false; } else { char ch = sta.peek(); if(ch == '(' && chs[i] == ')') { sta.pop(); } else if(ch == '{' && chs[i] == '}') { sta.pop(); } else if(ch == '[' && chs[i] == ']') { sta.pop(); } else { return false; } } } return sta.isEmpty(); } }
使用stack,解决问题很容易
import java.util.*; public class Solution { /** * * @param s string字符串 * @return bool布尔型 */ public boolean isValid(String s) { Stack<Character> stack = new Stack<>(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (!stack.isEmpty()) { if (c == ')' && stack.pop() == '(') { continue; } if (c == ']' && stack.pop() == '[') { continue; } if (c == '}' && stack.pop() == '{') { continue; } } stack.add(c); } return stack.isEmpty(); } }
public boolean isValid (String s) { // write code here //利用哈希存储字符,避免if语句中出现冗余比较语句 HashMap<Character, Character> map = new HashMap<Character, Character>() { { put(')', '('); put(']', '['); put('}', '{'); } }; Stack<Character> stack = new Stack<>(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (map.containsKey(c)) { if (stack.isEmpty()) return false; if (map.get(c) != stack.peek()) return false; stack.pop(); } else { stack.push(c); } } return stack.isEmpty(); }