2 hashmap with runtime of 2 ms in Java


  • 0
    H
        public boolean wordPattern(String pattern, String str) {
            if(pattern == null || str == null)
                return false;
            if(pattern.length() == 0 || str.length() == 0)
                return false;
            String[] words = str.split(" ");
            char[] p = pattern.toCharArray();
            if(p.length != words.length)
                return false;
            Map<String,Character> map = new HashMap<>();
            Map<Character,String> sMap = new HashMap<>();
            for(int i = 0; i < p.length; i++){
                if(map.containsKey(words[i])){
                    char ch = map.get(words[i]);
                    if(ch != p[i])
                        return false;
                }else{
                    if(sMap.containsKey(p[i])){
                        String word = sMap.get(p[i]);
                        if(!word.equals(words[i]))
                            return false;
                    }
                    sMap.put(p[i],words[i]);
                    map.put(words[i],p[i]);
                }
            }
            return true;
        }
    
    

Log in to reply
 

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