LeetCode(50)-Word Pattern

时间:2023-03-09 05:48:27
LeetCode(50)-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.

思路:

  • 题意:给定一个字符串a,这个字符串的字符给定了一种模式,然后给定一个字符串b其中把字符串用空格隔开,判断b是否和a的格式一样,a里面的字符相同,b也要相同,a不同,b也不同,同时位置也一样
  • 采用的方法是a,转化为数组aa,bb,建立map,b根据空格,转化位数组,把a的存进map,判断map.containsKey(),包含去掉上一个重复值,添加新值,同时bb的相应位置元素也相同,不同的话,map.put,然后判断bb的元素和以前的都不同

    -注意长度相同,同时都为空时返回true

代码:

public class Solution {
    public boolean wordPattern(String pattern, String str) {
        Map<Character,Integer> pp = new HashMap<Character,Integer>();
        if(pattern == null && str == null){
            return true;
        }
        char[] p = pattern.toCharArray();
        String[] s = str.split(" ");
        if(p.length != s.length){
            return false;
        }else{
            for(int i = 0;i < p.length;i++){
                if(pp.containsKey(p[i])){
                    int k = pp.get(p[i]);
                    pp.remove(p[i]);
                    pp.put(p[i],i);
                    if(!s[k].equals(s[i])){
                        return false;
                    }
                }else{
                    pp.put(p[i],i);
                    for(int a = 0;a < i;a++){
                        if(s[a].equals(s[i])){
                            return false;
                        }
                    }
                }
            }
        }
        return true;
    }
}