3.TDD实现成对扩符问题

1.题目:

Write a program to determine if the the parentheses (),the brackets [], and the braces {}, in a string are balanced.For example:
{{)(}} is not balanced because ) comes before (
({)} is not balanced because ) is not balanced between {} and similarly the { is not balanced between ()
[({})] is balanced
{}([]) is balanced
{()}[[{}]] is balanced
编写一个程序来确定括号(),字符串中的括号[]和大括号{}是平衡的。例如:
{{)(}}不平衡,因为)在(({)}不平衡是因为){}之间不平衡同样,{在()之间是不平衡的
({ })是平衡的
{ }([])是平衡的
{()}({ })是平衡的

2.TDD代码

package cs.balance;

import org.junit.Test;

import cs.balanced.ParenthesesBalance;
import junit.framework.Assert;

public class ParenthesesBalanceTest {
    @Test
    public void 只有一个字符() throws Exception {
        //given
        String givenString = "{";
        boolean booleanGiven = false;
        ParenthesesBalance balance = new ParenthesesBalance();

        //when
        boolean booleanReturn = balance.judgeBalance(givenString);

        //then
        Assert.assertEquals(booleanGiven, booleanReturn);
    }

    @Test
    public void 有两个字符() throws Exception {
        //given
        String givenString = "{}";
        boolean booleanGiven = true;
        ParenthesesBalance balance = new ParenthesesBalance();

        //when
        boolean booleanReturn = balance.judgeBalance(givenString);

        //then
        Assert.assertEquals(booleanGiven, booleanReturn);
    }

    @Test
    public void 有N个字符() throws Exception {
        //given
        String givenString = "{[[[{}()]]][]}";
        boolean booleanGiven = true;
        ParenthesesBalance balance = new ParenthesesBalance();

        //when
        boolean booleanReturn = balance.judgeBalance(givenString);

        //then
        Assert.assertEquals(booleanGiven, booleanReturn);
    }
}   

3.实现代码

package cs.balanced;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

import org.springframework.util.Assert;

import cs.constant.Constants;

/**
 * 
 * @author shuai.chen
 * @date 2018年9月11日
 * @Description
 * Write a program to determine if the the parentheses (),
 * the brackets [], and the braces {}, in a string are balanced.
 *  For example:
 *      {{)(}} is not balanced because ) comes before (
 *      ({)} is not balanced because ) is not balanced between {} and similarly the { is not balanced between ()
 *      
 *      [({})] is balanced
 *      {}([]) is balanced
 *      {()}[[{}]] is balanced
 *      
 *      编写一个程序来确定括号(),字符串中的括号[]和大括号{}是平衡的。例如:
 *      {{)(}}不平衡,因为)在(({)}不平衡是因为){}之间不平衡同样,{在()之间是不平衡的
 *      
 *      ({ })是平衡的
 *      { }([])是平衡的
 *      {()}({ })是平衡的
 *      
 */
public class ParenthesesBalance {
    public boolean judgeBalance(String givenString) throws Exception{
        List<String> list = new ArrayList<>();
        int index = -1;

        /** 1.入参非空检验*/
        Assert.hasText(givenString, Constants.BALANCE_STRING_EXCEPTION);

        /** 2.计算字符串真实大小 */
        int actLen = 0;
        for (int i = 0; i < givenString.length(); i++) {
            if (!Character.isWhitespace(givenString.charAt(i))) {
                actLen++;
            }
        }

        /** 3.处理字符串    */
        if(actLen == 0) {
            throw new Exception();
        }
        if(actLen % 2 == 1) {
            return false;
        }
        if(actLen % 2 == 0) {
            for (int i = 0; i < givenString.length(); i++) {
                if (!Character.isWhitespace(givenString.charAt(i))) {
                    if(String.valueOf(givenString.charAt(i)).equals("{")) {
                        list.add("3");
                        index++;
                    }
                    if(String.valueOf(givenString.charAt(i)).equals("[")) {
                        list.add("2");
                        index++;
                    }
                    if(String.valueOf(givenString.charAt(i)).equals("(")) {
                        list.add("1");
                        index++;
                    }
                    if(String.valueOf(givenString.charAt(i)).equals("}")) {
                        if(list.size() == 0) {
                            return false;
                        }
                        if(!list.remove(index--).equals("3")) {
                            return false;
                        }
                    }
                    if(String.valueOf(givenString.charAt(i)).equals("]")) {
                        if(list.size() == 0) {
                            return false;
                        }
                        if(!list.remove(index--).equals("2")) {
                            return false;
                        }
                    }
                    if(String.valueOf(givenString.charAt(i)).equals(")")) {
                        if(list.size() == 0) {
                            return false;
                        }
                        if(!list.remove(index--).equals("1")) {
                            return false;
                        }
                    }
                }
            }
        }
        return true;
    }

    /**使用Stack重复实现*/
    public boolean judgeBalance2(String givenString) throws Exception{
        Stack<String> stack = new Stack<>();
        int index = -1;

        /** 1.入参非空检验*/
        Assert.hasText(givenString, Constants.BALANCE_STRING_EXCEPTION);

        /** 2.计算字符串真实大小 */
        int actLen = 0;
        for (int i = 0; i < givenString.length(); i++) {
            if (!Character.isWhitespace(givenString.charAt(i))) {
                actLen++;
            }
        }

        /** 3.处理字符串    */
        if(actLen == 0) {
            throw new Exception();
        }
        if(actLen % 2 == 1) {
            return false;
        }
        if(actLen % 2 == 0) {
            for (int i = 0; i < givenString.length(); i++) {
                if (!Character.isWhitespace(givenString.charAt(i))) {
                    if(String.valueOf(givenString.charAt(i)).equals("{")) {
                        stack.push("3");
                        index++;
                    }
                    if(String.valueOf(givenString.charAt(i)).equals("[")) {
                        stack.push("2");
                        index++;
                    }
                    if(String.valueOf(givenString.charAt(i)).equals("(")) {
                        stack.push("1");
                        index++;
                    }
                    if(String.valueOf(givenString.charAt(i)).equals("}")) {
                        if(stack.empty()) {
                            return false;
                        }
                        if(!stack.pop().equals("3")) {
                            return false;
                        }
                        index--;
                    }
                    if(String.valueOf(givenString.charAt(i)).equals("]")) {
                        if(stack.empty()) {
                            return false;
                        }
                        if(!stack.pop().equals("2")) {
                            return false;
                        }
                        index--;
                    }
                    if(String.valueOf(givenString.charAt(i)).equals(")")) {
                        if(stack.empty()) {
                            return false;
                        }
                        if(!stack.pop().equals("1")) {
                            return false;
                        }
                        index--;
                    }
                }
            }
        }
        return true;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值