zoukankan      html  css  js  c++  java
  • LeetCode -- Word Pattern

    Question:

    Given a pattern and a string str, find if str follows the same pattern.

    Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.

    Examples:

    1. pattern = "abba", str = "dog cat cat dog" should return true.
    2. pattern = "abba", str = "dog cat cat fish" should return false.
    3. pattern = "aaaa", str = "dog cat cat dog" should return false.
    4. pattern = "abba", str = "dog dog dog dog" should return false.

    Notes:
    You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

    Analysis:

     给出一个“pattern”和一个字符串,判断字符串是否跟pattern一致。

    下面给出了几个patter-str的例子。

    思路:根据上面给出的几个例子可以得知,单个字符与字符串以一对一的形式出现,而且位置也要对应。因此可以用一个哈希map控制两者的对应。但是HashMap只能保证key值不重复出现,不能保证value不重复。因此还需要额外的一个set来控制String的单一。

    Answer:

    public class Solution {
        public boolean wordPattern(String pattern, String str) {
                Map<Character, String> map = new HashMap<Character, String> ();
                Set<String> set = new HashSet<String>();
                char[] ch = pattern.toCharArray();
                String[] strr = str.split(" ");
                if(ch.length != strr.length)
                    return false;
                for(int i=0; i<ch.length; i++) {
                    if(!map.containsKey(ch[i]) && !set.contains(strr[i])) {
                        map.put(ch[i], strr[i]);
                        set.add(strr[i]);
                    } else {
                        if(set.contains(strr[i]) && !map.containsKey(ch[i]))
                            return false;
                        if(!map.get(ch[i]).equals(strr[i]))
                            return false;
                    }
                }
                return true;
        }
        
    }
  • 相关阅读:
    284. Peeking Iterator
    283. Move Zeroes
    282. Expression Add Operators
    281. Zigzag Iterator
    280. Wiggle Sort
    279. Perfect Squares
    python 正则匹配替换,在匹配的字符后方添加新的字符
    odoo default_get 方法和onchange装饰器造成冲突,
    redmine 如何启用用户图标
    odoo 打印执行的sql语句
  • 原文地址:https://www.cnblogs.com/little-YTMM/p/4940288.html
Copyright © 2011-2022 走看看