標籤:
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
LeetCode:Word Pattern - 字串模式比對