Straightforward Java solution with hashmap


  • 0
    K
    tips: always remember to use .equals() to compare string content
    
    public class Solution {
        public boolean wordPattern(String pattern, String str) {
            str = str.trim();
            String[] s = str.split(" ");
            //for(String j : s) System.out.print(j + " ");
            int len1 = pattern.length();
            int len2 = s.length;
            if(len1 != len2) return false;
            HashMap<Character,String> hm = new HashMap<>();
            for(int i = 0; i < len1; i++){
                char m = pattern.charAt(i);
                String n = s[i];
                if((hm.containsKey(m) && !hm.get(m).equals(n)) ||(!hm.containsKey(m) && hm.containsValue(n))) return false;
                else if(hm.containsKey(m) && hm.get(m).equals(n)) continue;
                else if(!hm.containsKey(m) && !hm.containsValue(n)) hm.put(m,n);
            }
            return true;
        }
    }

Log in to reply
 

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