Java Time O(n) and Space O(n) HashMap Solution


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

  • 0
    L

    @polluxgx This is not O(n) time, containsValue is O(n) itself


Log in to reply
 

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