如數一組字符串,看是否符合一下兩個條件: 1、字符只有(和) 2、看(和)是否匹配 如:輸入:((1)) 返回false 輸入:((()) 返回false 輸入:(()) 返回true
思路:先用toCharArray方法把字符串拆成一個數組,然後遍歷數組的每一個元素,若遇到左括號,就入棧,若遇到右括號,就去棧裏找,看有沒有左括號與之匹配
1、用stack.push()入棧,stack.pop()出棧
2、若遇到右括號,去棧裏找,棧爲空,rerturn false
3、若最後一個元素爲左括號,return false
4、遍歷完,檢查stack是否爲空,其實第3步可以剩,因爲4以及包含了這種情況
import java.util.Stack;
import java.util.*;
public class Parenthesis {
public static boolean chkParenthesis(String A, int n) {
// write code here
Stack stack=new Stack();
char[] b=A.toCharArray();//把字符串拆成數組
for(int i=0;i<n;i++){
if(b[i]=='('){ //如果遍歷到( 就入棧
stack.push(b[i]);
}
if(b[i]==')'){ //如果遍歷到)就去棧內查看是否爲空,如果爲空,說明沒有(與之匹配,return false,如果不爲空,提取一個(出來
if (!stack.isEmpty()){
stack.pop();
}
else {
return false;
}
}
if(b[n-1]=='('){ //如果最後一個是(,說明沒有)與之匹配,return false
return false;
}
}
if(!stack.isEmpty()){ //爲防止還兩個及兩個以上的(多出來,遍歷完所有之後,再檢查數組,如果還有剩餘,return false
return false;
}else {
return true;
}
}
public static void main(String[] args) {
String A="(()))";
int n=5;
System.out.println(chkParenthesis(A,n));
}
}