文章 224
评论 6
浏览 200762
String - 290. Word Pattern

String - 290. Word Pattern

290. Word Pattern

Given two strings s and _t _, write a function to determine if t is an anagram of s.

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: false

Note:
You may assume the string contains only lowercase alphabets.

Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?

思路:

题目的实质是两个数组相同元素的索引匹配,可以抽象为两个数组,分别记录某个元素在源字符串中的下标。这里用map来做,因为put的操作,如果空值就返回null,否则返回之前存储的value;

代码:

java:

class Solution {

    public boolean wordPattern(String pattern, String str) {
        if (pattern == null || str == null) return true;
        
        String[] strs = str.split(" ");
        if (strs.length != pattern.length()) return false;
        
        Map index = new HashMap();
        for (Integer i = 0; i < strs.length; i++) {
            if (index.put(pattern.charAt(i), i) != index.put(strs[i], i)) // return null or old value
                return false;
        }
        
        return true;
    }
}

标题:String - 290. Word Pattern
作者:michael
地址:https://www.bitbo-liuyang.com/articles/2019/06/29/1561815272817.html

Nothing just happens, it's all part of a plan.

取消