码迷,mamicode.com
首页 > 其他好文 > 详细

两个关于栈的应用例子

时间:2019-11-30 22:50:34      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:arm   pre   function   stack   throws   illegal   ase   pen   static   

package DataStructures.Stacks;

import java.util.Stack;

public class DecimalToAnyUsingStack {
    public static void main(String[] args) {
        assert convert(0, 2).equals("0");
        assert convert(30, 2).equals("11110");
        assert convert(30, 8).equals("36");
        assert convert(30, 10).equals("30");
        assert convert(30, 16).equals("1E");
    }

    /**
     * Convert decimal number to another radix
     *
     * @param number the number to be converted
     * @param radix the radix
     * @return another radix
     * @throws ArithmeticException if <tt>number</tt> or <tt>radius</tt> is invalid
     */
    private static String convert(int number, int radix) {
        if (radix < 2 || radix > 16) {
            throw new ArithmeticException(
                    String.format("Invalid input -> number:%d,radius:%d", number, radix));
        }
        char[] tables = {
                ‘0‘, ‘1‘, ‘2‘, ‘3‘, ‘4‘,
                ‘5‘, ‘6‘, ‘7‘, ‘8‘, ‘9‘,
                ‘A‘, ‘B‘, ‘C‘, ‘D‘, ‘E‘, ‘F‘
        };
        Stack<Character> bits = new Stack<>();
        do {
            bits.push(tables[number % radix]);
            number = number / radix;
        } while (number != 0);

        StringBuilder result = new StringBuilder();
        while (!bits.isEmpty()) {
            result.append(bits.pop());
        }
        return result.toString();
    }
}

这个就是利用栈来进行进制转换

 

package DataStructures.Stacks;

import java.util.Stack;

/**
 * The nested brackets problem is a problem that determines if a sequence of
 * brackets are properly nested. A sequence of brackets s is considered properly
 * nested if any of the following conditions are true: - s is empty - s has the
 * form (U) or [U] or {U} where U is a properly nested string - s has the form
 * VW where V and W are properly nested strings For example, the string
 * "()()[()]" is properly nested but "[(()]" is not. The function called
 * is_balanced takes as input a string S which is a sequence of brackets and
 * returns true if S is nested and false otherwise.
 *
 * @author akshay sharma
 * @author <a href="https://github.com/khalil2535">khalil2535<a>
 * @author shellhub
 */
class BalancedBrackets {

    /**
     * Check if {@code leftBracket} and {@code rightBracket} is paired or not
     *
     * @param leftBracket   left bracket
     * @param rightBracket right bracket
     * @return {@code true} if {@code leftBracket} and {@code rightBracket} is paired,
     * otherwise {@code false}
     */
    public static boolean isPaired(char leftBracket, char rightBracket) {
        char[][] pairedBrackets = {
                {‘(‘, ‘)‘},
                {‘[‘, ‘]‘},
                {‘{‘, ‘}‘},
                {‘<‘, ‘>‘}
        };
        for (char[] pairedBracket : pairedBrackets) {
            if (pairedBracket[0] == leftBracket && pairedBracket[1] == rightBracket) {
                return true;
            }
        }
        return false;
    }

    /**
     * Check if {@code brackets} is balanced
     *
     * @param brackets the brackets
     * @return {@code true} if {@code brackets} is balanced, otherwise {@code false}
     */
    public static boolean isBalanced(String brackets) {
        if (brackets == null) {
            throw new IllegalArgumentException("brackets is null");
        }
        Stack<Character> bracketsStack = new Stack<>();
        for (char bracket : brackets.toCharArray()) {
            switch (bracket) {
                case ‘(‘:
                case ‘[‘:
                case ‘{‘:
                    bracketsStack.push(bracket);
                    break;
                case ‘)‘:
                case ‘]‘:
                case ‘}‘:
                    if (bracketsStack.isEmpty() || !isPaired(bracketsStack.pop(), bracket)) {
                        return false;
                    }
                    break;
                default: /* other character is invalid */
                    return false;
            }
        }
        return bracketsStack.isEmpty();
    }


    public static void main(String[] args) {
        assert isBalanced("[()]{}{[()()]()}");
        assert !isBalanced("[(])");
    }
}

匹配括号

 

比较简单,今天主要在学习函数式编程。

两个关于栈的应用例子

标签:arm   pre   function   stack   throws   illegal   ase   pen   static   

原文地址:https://www.cnblogs.com/CherryTab/p/11964307.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!