My clear and Short java solution using two maps


  • 0
    C
    public class Solution {
        public boolean wordPattern(String pattern, String str) {
             String[] strs = str.split(" ");
            if(pattern.length()!=strs.length) return false;
            Map<Character, String> map = new HashMap<Character, String>();
            Map<String, Boolean> assigned = new HashMap<String, Boolean>();
            for(int i=0; i<strs.length;i++){
                String val = map.put(pattern.charAt(i), strs[i]);
                if(val!=null && !val.equals(strs[i])) return false;
                if(val==null){
                    if(assigned.put(strs[i], true)!=null) return false;
                }
            }
            return true;
        }
    }
    

Log in to reply
 

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