JAVA easy to understand solution


  • 4
    V

    public class Solution {

    public boolean wordPattern(String pattern, String str) {
        Map<Character, String> map = new HashMap<Character, String>();
        
        String[] words = str.split(" ");
        
        if(pattern.length() != words.length) {
            return false;
        }
        
        else {
            for(int i = 0; i < pattern.length(); i++) {
                if(map.containsKey(pattern.charAt(i))) {
                    if(!map.get(pattern.charAt(i)).equals(words[i])) {
                        return false;
                    }
                }
                else {
                    if(map.containsValue(words[i])) {
                        return false;
                    }
                    map.put(pattern.charAt(i), words[i]);
                }
            }
        }
        return true;
    }
    

    }


  • 0
    L

    containsValue is not as good as maintaining another hashmap


  • 1
    A
    public boolean wordPattern(String pattern, String str) {
        HashMap<String,Character> map1 = new HashMap<String,Character>();
        HashMap<Character,String> map2 = new HashMap<Character,String>();
        
        StringTokenizer tokenizer = new StringTokenizer(str);
        
        if (tokenizer.countTokens() != pattern.length()) { 
            return false;
        }
        for(Character c : pattern.toCharArray()) {
            String nextToken = tokenizer.nextToken();
            
            if (map1.containsKey(nextToken)) {
                if (!map1.get(nextToken).equals(c)) return false;
            } else {
                map1.put(nextToken, c);
            }
            
            if (map2.containsKey(c)) {
                if (!map2.get(c).equals(nextToken)) return false;
            } else {
                map2.put(c, nextToken);
            }
        }
        
        return true;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.