[Leetcode] Word Pattern 单词模式
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; }}