昨天朋友笔试,大家做着玩的题
首先,会给我们一个已经括号匹配的串,然后成对去掉,问有多少种情况,具体可以看一下下图。
java代码:
public class Main5 {
static boolean isMatch(String s) {
Stack<Character> sk = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
sk.push('(');
}
if (s.charAt(i) == ')') {
if (!sk.isEmpty() && sk.pop() == '(')
continue;
else
return false;
}
}
if (sk.isEmpty())
return true;
else
return false;
}
public static String ArrayListToString(ArrayList<Character> list) {
String result = "";
for (int i = 0; i < list.size(); i++) {
result += list.get(i);
}
return result;
}
public static int Dong2(String text) {
int result = 1;
int count = 0;
int charsCount = text.length();
char[] chars = text.toCharArray();
int where = 0;
ArrayList<Character> list = new ArrayList<Character>();
for (int i = 0; i < charsCount; i++) {
list.add(chars[i]);
}
while (list.contains('(')) {
list.remove(0);
for (int j = 0; j < list.size(); j++) {
Character character = list.remove(j);
if (isMatch(ArrayListToString(list))) {
count++;
where = j;
}
list.add(j, character);
}
list.remove(where);
result = result * count;
count = 0;
}
return result;
}
public static void main(String[] args) {
System.out.println(Dong2("(((())))"));
System.out.println(Dong2("((()))"));
System.out.println(Dong2("(())"));
System.out.println(Dong2("()()()"));
}
}
输出:
24
6
2
1