首页 > 代码库 > LeetCode-Word Pattern
LeetCode-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.
Credits:
Special thanks to @minglotus6 for adding this problem and creating all test cases.
Solution:
public class Solution { public boolean wordPattern(String pattern, String str) { if (str.isEmpty() && pattern.isEmpty()) return true; if (str.isEmpty() || pattern.isEmpty()) return false; String[] map = new String[26]; Arrays.fill(map,""); String[] words = str.split(" "); HashSet<String> assigned = new HashSet<String>(); if (pattern.length()!=words.length) return false; for (int i=0;i<pattern.length();i++){ char code = pattern.charAt(i); if (!map[code-‘a‘].isEmpty()){ // code.word != word, it is wrong if (!map[code-‘a‘].equals(words[i])){ return false; } } else { // code.word is empty but word has been assigned to another code, it is wrong. if (assigned.contains(words[i])){ return false; } assigned.add(words[i]); map[code-‘a‘] = words[i]; } } return true; }}
LeetCode-Word Pattern
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。