My 1ms Java solution may help u


  • -1
    B
    public class Solution {
        public boolean wordPattern(String pattern, String str) {
    		int len = pattern.length();
    		String[] strs = str.split(" ");
    		int size = strs.length;
    		if (len != size)
    			return false;
    		String[] map = new String[26];
    		HashSet<String> set = new HashSet<String>();
    		for (int i = 0; i < len; ++i) {
    			int idx = pattern.charAt(i) - 'a';
    			String s = strs[i];
    			if (map[idx] == null) {
    				if (set.contains(s))
    					return false;
    				map[idx] = s;
    				set.add(s);
    			} else if (!map[idx].equals(s))
    				return false;
    		}
    		return true;
    	}
    }

Log in to reply
 

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