algorithm 1.3.4 1.3.9 solutions

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)))"));
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值