my implementation, beats 48%


  • 0
    S
        public boolean wordPattern(String pattern, String str) {
            List<String> list = new LinkedList<String>();
            Map<Character, String> map = new HashMap<Character, String>();
            Set<String> set = new HashSet<String>();
            int start = 0;
            for(int end = 0; end < str.length(); end++) {
                if(str.charAt(end) != ' ') {
                    if(end == str.length()-1) {
                        list.add(str.substring(start, str.length()));
                    }
                }else {
                    list.add(str.substring(start, end));
                    if(end+1<str.length()) {
                         start = end+1;
                   }
                
                }
            }
            if(pattern.length() != list.size()) {
                return false;
            }
      
            for(int i = 0; i < pattern.length(); i++) {
                if(!map.containsKey(pattern.charAt(i))) {
                    if(set.contains(list.get(i))) {
                        return false;
                    }
                    map.put(pattern.charAt(i), list.get(i));
                    set.add(list.get(i));
                } else {
                    if(!map.get(pattern.charAt(i)).equals(list.get(i))) {
                         return false;
                    }
               
                }
             }
            return true;
         }

Log in to reply
 

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