My 2ms Java Solution


  • 0
    G
    import java.util.HashMap;
    import java.util.Map;
    import java.util.StringTokenizer;
    
    public class Solution {
        public boolean wordPattern(String pattern, String str) {
            
            char c[] = pattern.toCharArray();
            
            Map <String,String> patternMap = new HashMap<String,String>();
            boolean retValue = false;
            
            StringTokenizer st = new StringTokenizer(str, " ");
            
            String strArray[] = new String[st.countTokens()];
            int count=0;
            while(st.hasMoreTokens()) {
            	strArray[count++] = 	st.nextToken();
            	
            }
            
            if(strArray.length!=c.length) {
            	return retValue;
            }
            
            for(int i=0;i<c.length;i++) {
            	retValue=true;
            	if(!patternMap.containsKey(c[i]+"")) {
            		Iterator<String> it = patternMap.values().iterator(); 
            		while (it.hasNext()) {
            			String value = it.next();
            			if(value.equalsIgnoreCase(strArray[i])) {
            				retValue =false;
            			 break;
            			}
            		}
            		if(retValue) {
            			patternMap.put(c[i]+"", strArray[i]);
            		} else {
            			break;
            		}
            		
            	}
            	else {
            		String value = patternMap.get(c[i]+"");
            		if(!value.equalsIgnoreCase(strArray[i])) {
            			retValue=false;
            			break;
            		}
            	}
            }
            
            return retValue;
        
        }
    }

Log in to reply
 

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