解いたコード
- 前回に引き続き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 {
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;
}
}
}
if (this.Stack.Count > 0) {
return false;
}
} catch (InvalidOperationException e) {
return false;
}
return true;
}
}
Problem2
leetcode.com
Solution
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;
}
}