题解 | #有效括号序列#

有效括号序列

http://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2

import java.util.*;


public class Solution {
    /**
     * 
     * @param s string字符串 
     * @return bool布尔型
     */
    public boolean isValid (String s) {
        int sLen = s.length();
        if (sLen % 2 == 1) return false;
        // write code here
        LinkedListStack<Character> stack = new LinkedListStack<>();

        for (int i = 0; i < sLen; ++i) {
            Character top = stack.top();
            Character charAt = s.charAt(i);
            if (top != null && ((top == '(' && charAt == ')') || (top == '[' && charAt == ']') || (top == '{' && charAt == '}'))) {
                stack.pop();
            }
            else {
                if (charAt == ')' || charAt == ']' || charAt == '}') { return false; }
                stack.push(charAt);
            }
        }
        return stack.isEmpty();
    }
}

/////////////////////链表
/**
 * 栈的实现 -- 链表
 * 优点: 使用灵活方便, 只要有需要的时候才会申请空间
 * 缺点: 除了要存储元素外, 还需要额外存储指针(引用)信息
 * @param <T>
 */
class Node<T> {
    T data;
    Node<T> next;
}

class LinkedListStack<T> {
    private Node<T> pHead;

    public LinkedListStack() {
        pHead = new Node<T>();
        pHead.data = null;
        pHead.next = null;
    }

    public int size() {
        int size = 0;
        Node<T> cur = pHead.next;

        while (cur != null) {
            cur = cur.next;
            size++;
        }
        return size;
    }


    public T pop() {
        Node<T> popNode = pHead.next;
        if (popNode == null) return null;
        pHead.next = popNode.next;
        return popNode.data;
    }

    public T top() {
        Node<T> topNode = pHead.next;
        if (topNode == null) return null;
        return topNode.data;
    }

    public void push(T e) {
        Node<T> tlNode = new Node<>();
        tlNode.data = e;
        tlNode.next = pHead.next;
        pHead.next = tlNode;
    }

    public boolean isEmpty() {
        return pHead.next == null;
    }


}
/////////////////////链表

全部评论

相关推荐

xxxxOxo:该催就催,想要你的不会因为催就挂,催了就挂的是因为本来就要挂你
点赞 评论 收藏
分享
大叔叔1:你把自己说的话打码,所以你想表达什么
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务