1.3.4 solution
public class Parentheses {
public boolean isParentheses(String s) {
LinkedStack<Character> stack = new LinkedStack<Character>();
Map<Character, Character> pmap = new HashMap<Character, Character>() {
{
put('(', ')');
put('{', '}');
put('[', ']');
}
};
for (int i = 0; i < s.length(); i++) {
if (stack.top() != null && pmap.containsKey(stack.top()) && pmap.get(stack.top()) == s.charAt(i)) {
stack.pop();
} else {
stack.push(s.charAt(i));
}
}
return stack.isEmpty();
}
public static void main(String[]args){
System.out.println(new Parentheses().isParentheses("[{}[]"));
}
}
1.3.9 solution
采用两个栈,一个用来存储操作符,一个用来存储操作数;
有个小技巧,把(1+2)也当作操作数,并且采用String来整体存储一个操作数,我在刚开始的时候采用Character来存储操作结果,发现除了问题。
另外,这个补全的方法并没有按照+-/×的运算顺序进行括号添加,事实上,如果按照四则运算法则的话,会有多个括号匹配的方案,这个题目并不是这样的;
public class Exercises139 {
/**
* according to this exercises, there exist multi-solution.
*
*/
public String insertParentheses(String input) {
LinkedStack<String> stack1 = new LinkedStack<String>();
LinkedStack<String> stack2 = new LinkedStack<String>();
Map<String, Integer> mp = new HashMap<String, Integer>() {
/**
*
*/
private static final long serialVersionUID = 1L;
{
put("+", 1);
put("-", 1);
put("*", 2);
put("/", 2);
}
};
for (int i = 0; i < input.length();) {
String s = getString(input, i);
// System.out.println(s);
i += s.length();
if (s.equals(")")) {
String el1 = stack1.pop();
String el2 = stack1.pop();
String op = stack2.pop();
String ans = "(" + el2 + op + el1 + ")";
stack1.push(ans);
} else if (mp.containsKey(s)) {
stack2.push(s);
} else {
stack1.push(s);
}
}
while (!stack2.isEmpty()) {
String el1 = stack1.pop();
String el2 = stack1.pop();
String op = stack2.pop();
String ans = el2 + op + el1;
stack1.push(ans);
}
return stack1.pop();
}
public String getString(String s, int i) {
StringBuilder bd = new StringBuilder();
Set<Character> cset = new HashSet<Character>() {
/**
*
*/
private static final long serialVersionUID = 1L;
{
add('+');
add('-');
add('*');
add('/');
add(')');
}
};
boolean tt = false;
while (i < s.length() && !cset.contains(s.charAt(i))) {
bd.append(s.charAt(i++));
tt = true;
}
if (!tt) {
bd.append(s.charAt(i++));
}
return bd.toString();
}
public static void main(String[] args) {
System.out.println(new Exercises139().insertParentheses("1+2)*3-4)*5-6)))"));
}
}