LeetCodeのStack解いてみた

解いたコード

  • 前回に引き続きStackカテゴリの問題を解いてみた
    • コーディング面接対策のために解きたいLeetCode 60問 | 新井康平
  • C#で書いてます

Problem1

leetcode.com

Solution

public class Solution {
    private Stack<char> Stack = new Stack<char>();
    private Dictionary<char, char> Dictionary = new Dictionary<char, char>()
    {
        {')', '('},
        {'}', '{'},
        {']', '['},
    };
    
    
    public bool IsValid(string s) {
        try {
            // 1文字ずつよんでopen bracketであればstackに積む
            // close bracketであればstackから取り出し対応するものであれば処理を継続。そうでなければinvalidとする
            for (int i = 0; i < s.Length; i++) {
                if (this.Dictionary.ContainsValue(s[i])) {
                    this.Stack.Push(s[i]);                
                } else if (this.Dictionary.ContainsKey(s[i])) {
                    char c = this.Stack.Pop();
                    if (c == this.Dictionary[s[i]]) {
                        continue;
                    } else {
                        return false;
                    }
                }
            }
            
            // 「{」のようなinputに対応するため
            if (this.Stack.Count > 0) {
                return false;
            }
        } catch (InvalidOperationException e) {
            // popしたときに空だったときのため
            return false;
        }
        return true;
    }
}

Problem2

leetcode.com

Solution

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode ReverseList(ListNode head) {
        if (head == null) {
            return head;
        }

        Stack<int> Stack = new Stack<int>();
        ListNode current = head;
        while (current != null) {
            Stack.Push(current.val);
            current = current.next;
        }
        
        ListNode list = new ListNode(0);
        ListNode current1 = list;
        while (Stack.Count > 0) {
            int i = Stack.Pop();
            current1.val = i;
            
            if (Stack.Count > 0) {
                current1.next = new ListNode(0);
                current1 = current1.next;
            }
        }
        current1.next = null;
        return list;
    }
}