Java Solution without using HashMap


  • 0
    J
    public  boolean wordPattern(String pattern, String str) {
    	String word[] = str.split(" ");
    	char[] c = new char[pattern.length()];
    
    	for (int i = 0; i < pattern.length(); i++) {
    		c[i] = pattern.charAt(i);
    	}
    
    	if (pattern.length() != word.length) {
    		return false;
    	} else {
    		for (int i = 0; i < c.length; i++) {
    			for (int j = i + 1; j < c.length; j++) {
    				if (c[i] != c[j] && word[i].equals(word[j])) {
    					return false;
    				}
    				if (c[i] == c[j] && !word[i].equals(word[j])) {
    					return false;
    				}
    				if (c[i] == c[j] && word[i].equals(word[j])) {
    					continue;
    				}
    				if (c[i] != c[j] && !word[i].equals(word[j])) {
    					continue;
    				}
    			}
    		}
    	}
    
    	return true;
    }

  • 0
    B
    /**
     * 99.35% on 2016-01-19
     * @author badsheep
     * @param pattern
     * @param str
     * @return
     */
    public boolean wordPattern(String pattern, String str) {
    	
    	char[] patternArr = pattern.toCharArray();
    	char[] strArr = str.toCharArray();
    	
    	if(patternArr.length==0 && strArr.length==0){
    		return true;
    	}else if(patternArr.length!=0 && strArr.length!=0){
    		char[][] mapArr = new char[26][];
    		
    		int offset = 0;
    		int patternArrIndex = 0;
    		
    		char[] strPartTmp = null;
    		char[] strMapTmp = null;
    		
    		while(patternArrIndex < patternArr.length){
    			int from = patternArrIndex + offset;
    			if(from > strArr.length){
    				return false;
    			}
    			while((patternArrIndex + offset)<strArr.length && strArr[patternArrIndex + offset] != ' '){
    				offset++;
    			}
    			int to = patternArrIndex + offset;
    			strPartTmp = Arrays.copyOfRange(strArr, from, to);
    			strMapTmp = mapArr[patternArr[patternArrIndex]-97];
    			if(strMapTmp == null){
    				boolean ignore = false;
    				int m=0;
    				while(m<mapArr.length){
    					m++;
    					if(mapArr[m-1] == null) continue;
    					if(Arrays.equals(mapArr[m-1], strPartTmp)){
    						ignore = true;
    						break;
    					}
    				}
    				if(!ignore){
    					mapArr[patternArr[patternArrIndex]-97] = strPartTmp;
    				}else{
    					if((m - 1 + 97) != patternArr[patternArrIndex]){
    						return false;
    					}
    				}
    			}else{
    				if(!Arrays.equals(strMapTmp, strPartTmp)){
    					return false;
    				}
    			}
    			patternArrIndex++;
    		}
    		if(patternArrIndex + offset<strArr.length){
    			return false;
    		}
    		return true;
    	}else{
    		return false;
    	}
    }

Log in to reply
 

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