Java - 9 lines simple code (2ms)


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

Log in to reply
 

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