当前位置

网站首页> 程序设计 > 开源项目 > 程序开发 > 浏览文章

[Leetcode] Word Pattern 单词模式

作者:小梦 来源: 网络 时间: 2024-02-04 阅读:

Word Pattern

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

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: patterncontains only lowercase alphabetical letters, and str contains words separated by a single space. Each word in str contains only lowercase alphabetical letters. Both pattern and str do not have leading or trailing spaces. Each letter in pattern must map to a word with length that is at least 1.

哈希表法

复杂度

时间 O(N) 空间 O(N)

思路

这题几乎和Isomorphic Strings一模一样,不同的就是之前是字母映射字母,现在是字母映射字符串而已。

代码

public class Solution {    public boolean wordPattern(String pattern, String str) {        Map<Character, String> map = new HashMap<Character, String>();        Set<String> set = new HashSet<String>();        String[] pieces = str.split(" ");        if(pieces.length != pattern.length()) return false;        int i = 0;        for(String s : pieces){char p = pattern.charAt(i);System.out.println(p);if(map.containsKey(p)){    if(!s.equals(map.get(p))) return false;} else {    if(set.contains(s)) return false;    map.put(p, s);    set.add(s);}i++;        }        return true;    }}

热点阅读

网友最爱