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.实现代码
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.remove(index--).equals("3")) {
return false;
}
}
if(String.valueOf(givenString.charAt(i)).equals("]")) {
if(!list.remove(index--).equals("2")) {
return false;
}
}
if(String.valueOf(givenString.charAt(i)).equals(")")) {
if(!list.remove(index--).equals("1")) {
return false;
}
}
}
}
}
return true;
}
}