关闭

[leetcode]Word Pattern

174人阅读 评论(0) 收藏 举报
分类:

题目如下:

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/

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:20976次
    • 积分:1002
    • 等级:
    • 排名:千里之外
    • 原创:80篇
    • 转载:23篇
    • 译文:0篇
    • 评论:2条
    文章分类
    最新评论