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

编写一个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 背包、队列和栈-习题索引汇总

算法-第四版习题索引汇总

作者:马 岩Furzoom) (http://www.cnblogs.com/furzoom/
版权声明:本文的版权归作者与博客园共同所有。转载时请在明显地方注明本文的详细链接,未经作者同意请不要删除此段声明,感谢您为保护知识产权做出的贡献。
原文地址:https://www.cnblogs.com/furzoom/p/7710206.html