Unexpected error in my code, can someone help?


  • 0
    R
    public class Solution {
        public boolean wordPattern(String pattern, String str) {
            String[] words = str.split("\\s");
            if(pattern.length() != words.length) {
                return false;
            }
                Map<Character,Integer> patternMap = new HashMap<>();
                Map<String, Integer> wordMap = new HashMap<>();
                for(int i = 0 ; i< pattern.length(); i++){
                    Integer pValue = patternMap.put(pattern.charAt(i),i);
                    Integer wValue = wordMap.put(words[i], i);
                    if(pValue != null && wValue != null ){
                        if(pValue.intValue() != wValue.intValue()){
                            return false;
                        }
                        
                    }
                    //for handling null cases
                    if(pValue != wValue){
                        return false;
                    }
                    
                }
                return true;
            }
        }

  • 0
    R

    Figured it out.
    The following solution works:

    public class Solution {
        public boolean wordPattern(String pattern, String str) {
            String[] words = str.split("\\s");
            if(pattern.length() != words.length) {
                return false;
            }
                Map<Character,Integer> patternMap = new HashMap<>();
                Map<String, Integer> wordMap = new HashMap<>();
                for(int i = 0 ; i< pattern.length(); i++){
                    Integer pValue = patternMap.put(pattern.charAt(i),i);
                    Integer wValue = wordMap.put(words[i], i);
                    if(pValue != null && wValue != null ){
                        if(pValue.intValue() != wValue.intValue()){
                            return false;
                        }
    
                    }
                    //for handling null cases
                   else if(pValue != wValue){
                        return false;
                    }
    
                }
                return true;
            }
        } 

Log in to reply
 

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