A normal solution by java


  • 0
    S

    Remember the position of the pattrem first,then check the str with it.

    public class Solution {
        public boolean wordPattern(String pattern, String str) {
            String ss [] = str.split(" ");
            if(pattern.length()!=ss.length)
    	        	return false;
             Map<Object,ArrayList<Integer>> intMap = new HashMap<Object,ArrayList<Integer>>();
             for(int i=0;i<pattern.length();i++){
            	 if(intMap.containsKey(pattern.charAt(i)))
            	 {
            		 intMap.get(pattern.charAt(i)).add(i);
            	 }
            	 else
            	 {
            		 ArrayList tmpList = new ArrayList();
            		 tmpList.add(i);
            		 intMap.put(pattern.charAt(i),tmpList);
            	 }
             }
              Map<String,Integer> contain= new HashMap<String,Integer>();
              for(Map.Entry<Object,ArrayList<Integer>> entry:intMap.entrySet()){
            	 List<Integer> thisList = entry.getValue();
            	 String tmpS = ss[thisList.get(0)];
            	  if(contain.containsKey(tmpS)) return false;
    	          else contain.put(tmpS, 1);
            	 for(Integer position:thisList){
            		 if(!tmpS.equals(ss[position])){
                          return false;
            		 }
            	 }
             }
             return true;
        }
    }

Log in to reply
 

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