问题说明:
给(和)组成的字符串,判断该字符串中()是否成对出现,例如(),()(),(())。
解决方法:
使用栈的特性:先进后出
(1)遍历字符串,遇到(字符时,(进栈;遇到)时,将栈顶元素pop操作。
(2)遍历后若栈中有字符,则不匹配;若,栈为空,则字符串中()匹配
具体代码(java实现):
public class LeetcodeTest { public static void main(String[] args) { System.out.print("请输入()字符串:"); Scanner scanner=new Scanner(System.in); String s=scanner.nextLine(); Stack<Character> stack=new Stack<>(); char[] chars=s.toCharArray();
for (char ch :chars){ if (ch=='('){ stack.push(ch); }else if (ch==')'){ stack.pop(); }else { System.out.println(false); } } if (stack.isEmpty()){ System.out.println("匹配"); } } }
