2ms Java implementation


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

Log in to reply
 

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