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;
    }
}
posted @ 2018-04-08 10:59  optor  阅读(111)  评论(0编辑  收藏  举报