第十七题
- 功能描述:判断一个字符串中的"( )"是否配对
- 输入:if(a.equals(a))
- 输出:true
import java.util.HashMap;
import java.util.Map;
public class Test01 {
public static void main(String[] args) {
String s = "if(a.equals(a))";
System.out.println(check1(s));
System.out.println(check2(s));
}
public static boolean check1(String strIn) {
char[] strInArr = strIn.toCharArray();
Map<Character, Integer> map = new HashMap<Character, Integer>();
for (int i = 0; i < strInArr.length; i++) {
Integer integer = map.get(strInArr[i]);
map.put(strInArr[i], integer == null ? 1 : integer + 1);
}
if (map.get('(') == map.get(')')) {
return true;
} else {
return false;
}
}
public static boolean check2(String strIn) {
char[] strInArr = strIn.toCharArray();
int count = 0;
for (int i = 0; i < strInArr.length; i++) {
if (strInArr[i] == '(') {
count++;
}
if (strInArr[i] == ')') {
count--;
}
}
if (count == 0) {
return true;
} else {
return false;
}
}
}