LeetCode算法题-C#代码实现-栈(一)

20. Valid Parentheses

有效的括号

解题思路

将括号比较后者后,不同的入栈,相同的出栈,最后字符串遍历结束后栈为空则匹配成功。

public bool IsValid(string s) {
        //声明字典,括号匹配键值对
        Dictionary<char, char> dict = new Dictionary<char, char>();
        dict.Add(')', '(');
        dict.Add(']', '[');
        dict.Add('}', '{');
        Stack<char> stack = new Stack<char>();
        //遍历字符s,直到遍历s所有字符结束循环
        for (int i = 0; i < s.Length; i++)
        {
                //栈空则直接将下个字符入栈,结束本次循环
                if (stack.Count == 0)
                {
                        stack.Push(s[i]);
                        continue;
                }
                //获取字典中对应的括号,若和循环中s[i]相等则出栈,否则压入栈中
                char temp;
                dict.TryGetValue(s[i], out temp);
                if (stack.Peek() == temp)
                        stack.Pop();
                else
                        stack.Push(s[i]);
        }
        //遍历结束后若栈空,说明括号匹配
        if (stack.Count == 0)
                return true;
        else
                return false;
}

 

155. Min Stack

最小栈

解题思路

使用链栈,实现基本的入栈出栈,遍历栈中元素,同时比较其值,取其中最小,最后返回最小值。

public class MinStack {
    //结点类
    public class Node{
        public int val;
        public Node next;
        public Node(int item){
            val=item;
            next=null;
        }
        public Node(){
            val=0;
            next=null;
        }
    }
    //头结点指针和初始化
    Node head;
    /** initialize your data structure here. */
    public MinStack() {
        head=null;
    }
    //入栈方法,新入栈的结点成为head
    public void Push(int x) {
        if(head==null)
            head=new Node(x);
        Node p=new Node(x);
        p.next=head;
        head=p;
    }
    //出栈方法,head指向其后继结点
    public void Pop() {
        if(head==null)
            return;
        head=head.next;
    }
    //返回head的值
    public int Top() {
        return head.val;
    }
    //遍历链表,同时比较结点的值
    public int GetMin() {
        Node p=head;
        int minNum=int.MaxValue;
        while(p.next!=null){
            if(p.val<minNum){
                minNum=p.val;
            }
            p=p.next;
        }
        return minNum;
    }
}

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.Push(x);
 * obj.Pop();
 * int param_3 = obj.Top();
 * int param_4 = obj.GetMin();
 */

猜你喜欢

转载自www.cnblogs.com/errornull/p/9862709.html