Word Pattern

Given a pattern and a string str, find if str follows the same pattern.

Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.

Examples:
pattern = “abba”, str = “dog cat cat dog” should return true.
pattern = “abba”, str = “dog cat cat fish” should return false.
pattern = “aaaa”, str = “dog cat cat dog” should return false.
pattern = “abba”, str = “dog dog dog dog” should return false.

 

public class Solution {
    public boolean isValid(String s) {
        //since cases like "([])" also counts -> use stack 
        Stack<Character> stack = new Stack<Character> (); 
        int len = s.length(); 
        if (s == null || len == 0) return true; 
        if (len%2 != 0) return false; 
        for (int i = 0; i < len; i++) {
            char cur = s.charAt(i); 
            if (cur == '(' || cur == '{' || cur == '[' ) 
                stack.push(cur);
            else if (cur == ')' && !stack.empty() && stack.peek() == '(')
                stack.pop(); 
            else if (cur == '}' && !stack.empty() && stack.peek() == '{')
                stack.pop(); 
            else if (cur == ']' && !stack.empty() && stack.peek() == '[')
                stack.pop();
            else 
                return false; 
        }
        return stack.empty();
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s