zoukankan      html  css  js  c++  java
  • 290. Word Pattern

    原题链接:https://leetcode.com/problems/word-pattern/description/
    实现如下:

    import java.util.HashMap;
    import java.util.HashSet;
    import java.util.Map;
    import java.util.Set;
    
    /**
     * Created by clearbug on 2018/2/26.
     */
    public class Solution {
    
        public static void main(String[] args) {
            Solution s = new Solution();
    
            /**
             * Examples:
             pattern = "abba", str = "dog cat cat dog" should return true.
             pattern = "abba", str = "dog cat cat fish" should return false.
             pattern = "aaaa", str = "dog cat cat dog" should return false.
             pattern = "abba", str = "dog dog dog dog" should return false.
             */
            System.out.println(s.wordPattern("abba", "dog cat cat dog"));
            System.out.println(s.wordPattern("abba", "dog cat cat fish"));
            System.out.println(s.wordPattern("aaaa", "dog cat cat dog"));
            System.out.println(s.wordPattern("abba", "dog dog dog dog"));
        }
    
        /**
         * 方法一:使用内置哈希表
         *
         * Submission Detail: beats 25.66%
         * Runtime: 3 ms
         *
         * @param pattern
         * @param str
         * @return
         */
        public boolean wordPattern(String pattern, String str) {
            if (pattern == null || str == null) {
                return false;
            }
            Map<Character, String> map = new HashMap<>(pattern.length());
    
            char[] chars = pattern.toCharArray();
            String[] strings = str.split(" ");
            if (chars.length != strings.length) {
                return false;
            }
    
            for (int i = 0; i < chars.length; i++) {
                if (map.containsKey(chars[i])) {
                    String value = map.get(chars[i]);
                    if (!value.equals(strings[i])) {
                        return false;
                    }
                } else {
                    map.put(chars[i], strings[i]);
                }
            }
            Set<String> valueSet = new HashSet<>(map.values());
            if (map.keySet().size() != valueSet.size()) {
                return false;
            }
            return true;
        }
    }
    
  • 相关阅读:
    iOS中block实现的探究
    [ES6] 19. for ... of
    [ES6] 18. Map
    [ES6] 17. Set
    [ES6] 16. Object Enhancements
    [MEAN Stack] First API -- 5. Using $resource to setup REST app
    [AngularJS] Provider
    [MEAN Stack] First API -- 4. Organize app structure
    [AngularJS] ngCloak
    [Angular-Scaled Web] 9. Control your promises with $q
  • 原文地址:https://www.cnblogs.com/optor/p/8743683.html
Copyright © 2011-2022 走看看