Showing posts with label Stack. Show all posts
Showing posts with label Stack. Show all posts

Wednesday, January 1, 2014

[LeetCode] Valid Parentheses

Valid Parentheses
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

Analysis:
To find whether parentheses are paired correctly, a stack would be useful.
Scan from the start of string to its end.
When meeting '(','[','{', push them to stack.
When ')', ']', '}' is scanned, find its paired parentheses in the stack.
1) if the stack is empty, return false
2) if the top element in the stack cannot match, i.e. not paired in '(' with ')', '[' with ']' and '{' with '}', return false.
In the end, if the stack is empty, i.e. all parentheses are paired, return true. Other wise return false.

Monday, December 30, 2013

[LeetCode] Valid Palindrome

Link : Valid Palindrome


Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.

[LeetCode] Valid Parentheses


Link : Valid Parentheses

Analysis:
At first, I try to count number of each kind of parentheses in a variable, when meeting left part, increase by 1, and when meeting paired right part, decrease by 1.  If any variable below 0, return false. And if any count is not equal to 0, it is not a valid-parentheses string.

But the problem is the order of occurrence of different kind of parentheses. Counting only makes sure right part doesn't appear before left part, but cannot guarantee ([)] will return false.

I refer to http://blog.unieagle.net/2012/11/06/leetcode%E9%A2%98%E7%9B%AE%EF%BC%9Avalid-parentheses/.