题目链接:https://leetcode.com/problems/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
should return true.
cat cat dog" - pattern =
"abba"
, str ="dog
should return false.
cat cat fish" - pattern =
"aaaa"
, str ="dog
should return false.
cat cat dog" - pattern =
"abba"
, str ="dog
should return false.
dog dog dog"
Notes:
You may assume pattern
contains only lowercase letters, and str
contains
lowercase letters separated by a single space.
思路:
1、pattern字符相等的位置对应的字符串中的单词应该是相等的,pattern字符不相等的位置对应的字符串中单词应该也是不相等的。时间复杂度为
O(n^2),空间复杂度为O(1)。
2、用HashMap存储字符到单词的映射关系,时间复杂度为O(n),空间复杂度为O(n)。
算法1:
[java] view
plain copy
- public boolean wordPattern(String pattern, String str) {
- String strs[] = str.split(" ");
- char patterns[] = pattern.toCharArray();
- if (strs.length != patterns.length || strs.length == 0) {
- return false;
- }
- for (int i = 0; i < patterns.length; i++) {
- for (int j = i + 1; j < patterns.length; j++) {
- if (patterns[i] == patterns[j]) { // 字符相等的时候,单词应该相等
- if (!strs[i].equals(strs[j])) {
- return false;
- }
- } else { // 字符不相等的时候,单词也应该不相等
- if (strs[i].equals(strs[j])) {
- return false;
- }
- }
- }
- }
- return true;
- }
算法2:
[java] view
plain copy
- public boolean wordPattern(String pattern, String str) {
- String strs[] = str.split(" ");
- char patterns[] = pattern.toCharArray();
- HashMap<Character,String> map = new HashMap<Character,String>();
- HashMap<String,Character> map2 = new HashMap<String,Character>();
- if (strs.length != patterns.length || strs.length == 0) {
- return false;
- }
- for (int i = 0; i < patterns.length; i++) {
- if(!map.containsKey(patterns[i])){
- map.put(patterns[i], strs[i]);
- }else{
- if(!map.get(patterns[i]).equals(strs[i])){
- return false;
- }
- }
- if(!map2.containsKey(strs[i])){
- map2.put(strs[i], patterns[i]);
- }else{
- if(!map2.get(strs[i]).equals(patterns[i])){
- return false;
- }
- }
- }
- return true;
- }
时间: 2024-12-05 15:43:28