2ms Java solution


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

Log in to reply
 

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