1、题目名称
Word Pattern(字符串模式匹配)
2、题目地址
https://leetcode.com/problems/word-pattern/
3、题目内容
英文:Given a pattern
and a string str
, find if str
follows the same pattern.
中文:给出一组模式(pattern)和一个字符串(str),查看字符串是否与模式匹配
例如:
-
pattern = "abba",str = "dog cat cat dog",返回真
-
pattern = "abba",str = "dog cat cat fish",返回假
-
pattern = "aaaa",str = "dog cat cat dog",返回假
-
pattern = "abba",str = "dog dog dog dog",返回假
注意:
模式仅有小写字母构成,字符串被单个空格字符隔开,字符串中每个单词都由小写字母构成;模式和字符串的前后都不包含多余的空格;模式中的每个字母必须匹配一个字符串中长度至少为1的单词。
4、解题方法1
使用HashMap可以很方便地解决本问题。
需要注意的是,模式中的两个不同的字符,不能对应字符串中相同的单词。
Java代码如下:
import java.util.HashMap;
/**
* @功能说明:LeetCode 290 - Word Pattern
* @开发人员:Tsybius2014
* @开发时间:2015年10月9日
*/
public class Solution {
/**
* 字符串模式匹配
* @param pattern
* @param str
* @return
*/
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;
}
}
5、解题方法2
另一个办法需要利用HashMap中put函数的性质。
put函数的声明如下:
public V put(K key, V value)
它的功能是将键值对存入map中,如果map中原本就包含要插入的键,将旧值替换为新值。对于该函数的返回值,如果要插入的键在字典中不存在,则返回null,否则返回替换前的值。根据put函数的性质,可以作出如下Java代码:
import java.util.HashMap;
import java.util.Objects;
/**
* @功能说明:LeetCode 290 - Word Pattern
* @开发人员:Tsybius2014
* @开发时间:2015年10月9日
*/
public class Solution {
/**
* 模式匹配
* @param pattern
* @param str
* @return
*/
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;
}
@SuppressWarnings("rawtypes")
HashMap<Comparable, Integer> hashMap = new HashMap<Comparable, Integer>();
for (int i = 0; i < pattern.length(); i++) {
if (!Objects.equals(hashMap.put(pattern.charAt(i), i), hashMap.put(s[i], i)))
return false;
}
return true;
}
}
END