Simple and easy to understand Java Solution


  • 0
    D
    public class Solution {
    public boolean wordPattern(String pattern, String str) {
    Map<String, String> map = new HashMap<String, String>();
    	Queue<String> q = new LinkedList<String>();
    	String[] strs = str.split(" ");
    	char[] cs = pattern.toCharArray();
    	if (cs.length != strs.length)
    		return false;
    	for (int i = 0; i < cs.length; i++) {
    		q.offer(cs[i] + "");
    		if (map.get(cs[i]) == null && !map.containsValue(strs[i])) {
    			map.put(cs[i] + "", strs[i]);
    		}
    	}
    	StringBuffer sb = new StringBuffer();
    	for (String s : q) {
    		sb.append(map.get(s));
    		sb.append(" ");
    	}
    	sb.delete(sb.length() - 1, sb.length());
    	if (sb.toString().equals(str))
    		return true;
    	return false;
    }
    

    }


Log in to reply
 

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