问题:
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 assumepattern
contains only lowercase letters, and str
contains lowercase letters separated by a single space. 解决:
①使用hash map,键---pattern中的字符,值---str中的单词,每个pattern中的字符与str中的单词实现一一对应,不能重复映射。耗时3ms.
public class Solution {
public boolean wordPattern(String pattern, String str) {//每个pattern的字符对应str中的一个字符串 String[] s = str.split(" "); char[] pchar = pattern.toCharArray(); if (pchar.length != s.length) {//必须 return false; } Map<Character,String> map = new HashMap<>();//键---pattern中的字符,值---str中的词组 for (int i = 0;i < pchar.length ;i ++ ) { if (! map.containsKey(pchar[i])) { if (! map.containsValue(s[i])) {//验证没有已经映射过,也可以使用Set保存已经映射过的单词。 map.put(pchar[i],s[i]); }else{ return false; } }else{ if(! map.get(pchar[i]).equals(s[i])){ return false; } } } return true; } }②其实写法一样,但是这样效率会更高一些。
public class Solution {
public boolean wordPattern(String pattern, String str) { if (pattern.isEmpty() || str.isEmpty()) { return false; } String[] s = str.split(" "); if (s.length != pattern.length()) { return false; } HashMap<Character, String> hashMap = new HashMap<Character, String>(); for (int i = 0; i < pattern.length(); i++) { if (hashMap.containsKey(pattern.charAt(i))) { if (!hashMap.get(pattern.charAt(i)).equals(s[i])) { return false; } } else if (hashMap.containsValue(s[i])) { return false; } else { hashMap.put(pattern.charAt(i), s[i]); } } return true; } }