幸福的小骁仔的博客

不求闻达于诸侯,但求潜心做好技术

[leetcode]Word Pattern

题目如下:

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:
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.
Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

看到这个题目下意识地就选择用map,考虑以下几个问题:

  1. 初始输入的两个字符串,用split方法将后一个进行分割并保存在一个string类型的数组中,注意比较一下数组的长度与第一个字符串的长度是否相一致,不一致直接返回false(特殊情况的考虑);
  2. 在使用map时不单单要对key进行判断,还需要对value进行判断,否则会有特殊案例无法通过(因为这个WA了一遍)

毕竟是Easy题,附上代码:

public class Solution {
    public boolean wordPattern(String pattern, String str) {
        boolean flag = true;
            Map<Object, String> map = new HashMap();
            String []strArray = str.split(" ");
//          System.out.println(strArray.length);
            if(pattern.length() != strArray.length) return false;
            int index;
            char ch;
            for(index= 0; index < pattern.length(); index++){
                ch = pattern.charAt(index);
                if(map.containsKey(ch)){
                    String key = map.get(ch);
                    if(!key.equals(strArray[index])){
                        flag = false;
                        break;
                    }
                }
                else{
                    if(map.containsValue(strArray[index])){
                        flag = false;
                        break;
                    }
                    map.put(ch, strArray[index]);
                }
            }           
            return flag;
    }
}

题目链接:https://leetcode.com/problems/word-pattern/

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012505618/article/details/49934407
个人分类: leetcode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭