您的位置:首页 > 其它

算法-第四版-练习1.3.4解答

2016-09-28 16:07 134 查看
编写一个Stack的用例Parentheses,从标准输入读取一个文本流并使用栈判定其中的括号是否配对完整。例如,对于[()]{}{[()()]()} 程序应该打印true,对于 [(])则打印false。

/**
* Description :
* Author      : mn@furzoom.com
* Date        : Sep 28, 2016 3:43:48 PM
* Copyright (c) 2013-2016, http://furzoom.com All Rights Reserved.
*/
package com.furzoom.lab.algs.ch103;

import edu.princeton.cs.algs4.StdIn;

/**
* ClassName    : E10304 <br>
* Function     : TODO ADD FUNCTION. <br>
* date         : Sep 28, 2016 3:43:48 PM <br>
*
* @version
*/
public class E10304
{
public static boolean isValid(String input)
{
Stack<Character> s = new Stack<Character>();
int i;
for (i = 0; i < input.length(); i++)
{
char ch = input.charAt(i);
if (ch == '{' || ch == '(' || ch == '[')
{
s.push(ch);
}
else if (s.isEmpty())
{
break;
}
else if (ch == '}')
{
if ('{' != s.pop())
break;
}
else if (ch == ')')
{
if ('(' != s.pop())
break;
}
else if (ch == ']')
{
if ('[' != s.pop())
break;
}
else
{
// other character
}
}
return (i == input.length() && s.isEmpty());
}

public static void main(String[] args)
{
while (!StdIn.isEmpty())
{
String input = StdIn.readString();
if (isValid(input))
{
System.out.println("OK");
}
else
{
System.out.println("Invalid");
}
}
}

}


测试结果:

>java -cp ".;../lib/algs4.jar" com
.furzoom.lab.algs.ch103.E10304 < com/furzoom/lab/algs/ch103/E10304.txt
OK
Invalid
Invalid
Invalid


数据文件E10304.txt:

[()]{}{[()()]()}
[(])
[
]


算法-第四版-1.3 背包、队列和栈-习题索引汇总

算法-第四版习题索引汇总
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: