第十七题
- 功能描述:判断一个字符串中的"( )"是否配对
- 输入:if(a.equals(a))
- 输出:true
import java.util.HashMap;
import java.util.Map;
/**
* 功能描述:判断一个字符串中的"( )"是否配对
* 输入:if(a.equals(a))
* 输出:true
* @author lx
*
*/
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));
}
/**
* 写法一
* 算出左括号和右括号的个数进行对比
* @param strIn
* @return
*/
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;
}
}
/**
* 写法二
* 思路相同都是比较左括号和右括号的个数,但是写法上多扩展一个思路而已
* @param strIn
* @return
*/
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;
}
}
}
版权声明:本文为lenglovexu原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。