Wednesday, December 2, 2015

[leetcode]Word Pattern

最重要捉住1 to 1
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Solution {
    public boolean wordPattern(String pattern, String str) {
        if (pattern.length() == 0 || str.length() == 0) return false;

        String[] array = str.split(" ");
        if (array.length != pattern.length()) return false;
        HashMap<String, Character> lookup = new HashMap<String, Character>();
        HashMap<Character, String> reverseLookup = new HashMap<Character, String>();
        String result = "";
        for (int i = 0; i < array.length; i++){
            if(reverseLookup.containsKey(pattern.charAt(i)) && !reverseLookup.get(pattern.charAt(i)).equals(array[i])){
                return false;
            }else{
                reverseLookup.put(pattern.charAt(i), array[i]);
            }
            
            if(lookup.containsKey(array[i]) && lookup.get(array[i]) != pattern.charAt(i)){
                return false;    
            }else{
                lookup.put(array[i], pattern.charAt(i));
            }
        }
        return true;
    }
}

No comments:

Post a Comment