【LeetCode】290. Word Pattern 單詞規律(Easy)(JAVA)每日一題

吳中樂發表於2020-12-16

【LeetCode】290. Word Pattern 單詞規律(Easy)(JAVA)

題目地址: https://leetcode.com/problems/word-pattern/

題目描述:

Given a pattern and a string s, find if s 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 s.

Example 1:

Input: pattern = "abba", s = "dog cat cat dog"
Output: true

Example 2:

Input: pattern = "abba", s = "dog cat cat fish"
Output: false

Example 3:

Input: pattern = "aaaa", s = "dog cat cat dog"
Output: false

Example 4:

Input: pattern = "abba", s = "dog dog dog dog"
Output: false

Constraints:

  • 1 <= pattern.length <= 300
  • pattern contains only lower-case English letters.
  • 1 <= s.length <= 3000
  • s contains only lower-case English letters and spaces ’ '.
  • s does not contain any leading or trailing spaces.
  • All the words in s are separated by a single space.

題目大意

給定一種規律 pattern 和一個字串 str ,判斷 str 是否遵循相同的規律。

這裡的 遵循 指完全匹配,例如, pattern 裡的每個字母和字串 str 中的每個非空單詞之間存在著雙向連線的對應規律

說明:
你可以假設 pattern 只包含小寫字母, str 包含了由單個空格分隔的小寫字母。

解題方法

  1. 要字元和字串一一對應,不能是多對一也不能是一對多
  2. 把對應關係記錄下來,然後每次檢視是否相同即可
  3. note: 要考慮長度不一的問題
class Solution {
    public boolean wordPattern(String pattern, String s) {
        Map<Character, String> map = new HashMap<>();
        Set<String> set = new HashSet<>();
        int index = 0;
        for (int i = 0; i < pattern.length(); i++) {
            char ch = pattern.charAt(i);
            int start = index;
            if (index >= s.length()) return false;
            while (index < s.length() && s.charAt(index) != ' ') {
                index++;
            }
            String cur = s.substring(start, index);
            index++;
            String pre = map.get(ch);
            if (pre == null) {
                if (set.contains(cur)) return false;
                set.add(cur);
                map.put(ch, cur);
            } else {
                if (!pre.equals(cur)) return false;
            }
        }
        return index >= s.length();
    }
}

執行耗時:1 ms,擊敗了98.94% 的Java使用者
記憶體消耗:36.4 MB,擊敗了80.89% 的Java使用者

歡迎關注我的公眾號,LeetCode 每日一題更新
【LeetCode】290. Word Pattern 單詞規律(Easy)(JAVA)每日一題

相關文章