今天發現LintCode頁面刷新不出來了,因此就轉戰LeetCode。仍是像之前同樣,作題順序:難度從低到高,天天至少一題。數組
Given a pattern
and a string str
, find if str
follows the same pattern.spa
Here follow means a full match, such that there is a bijection between a letter in pattern
and a non-empty word in str
.code
Example 1:blog
Input: pattern = , str =
Output: true"abba""dog cat cat dog"
Example 2:字符串
Input:pattern = , str =
Output: false"abba""dog cat cat fish"
Example 3:string
Input: pattern = , str =
Output: false"aaaa""dog cat cat dog"
Example 4:hash
Input: pattern = , str =
Output: false"abba""dog dog dog dog"
Notes:
You may assume pattern
contains only lowercase letters, and str
contains lowercase letters separated by a single space.it
解題:題目給定倆字符串,第一個字符串是由若干非空字符組成,第二個字符串由若干單詞組成,用空白字符隔開。要求判斷兩組字符串格式是否相同。先貼一下本身寫的代碼吧,寫的代碼比較多,也沒啥技術含量。最主要的思想是,遍歷第一個字符串,比較各個位置上的字符是否相同,同時比較另外一個字符串相同位置的單詞是否相等,若是有不匹配的,返回false,遍歷結束時,返回true。代碼以下:io
1 class Solution { 2 public boolean wordPattern(String pattern, String str) { 3 4 if(pattern == null && str == null) 5 return true; 6 String []temp = str.split(" "); 7 8 if(pattern.length() != temp.length) 9 return false; 10 if(pattern.length() ==1) 11 return true; 12 for(int i = 1; i < pattern.length(); i++){ 13 for(int j = 0; j < i; j++){ 14 if(pattern.charAt(i) == pattern.charAt(j)){ 15 if(!equal(temp, i, j)){ 16 return false; 17 } 18 } 19 if(pattern.charAt(i) != pattern.charAt(j)){ 20 if(equal(temp, i, j)){ 21 return false; 22 } 23 } 24 } 25 } 26 return true; 27 28 } 29 public boolean equal(String[]temp,int index1,int index2){ 30 if(temp[index1].equals(temp[index2])){ 31 return true; 32 }else{ 33 return false; 34 } 35 } 36 37 } 38 }
在discussion上看到了更好的方法,用hash表來作的。hashmap中插入一組數據的方法是:public V put (K key, V value ) 若是插入一組數據時,已經有key存在,則返回 舊的value,並用新的value來覆蓋舊的value。class
那麼用一個循環同時遍歷兩個String,若是相同位置有重複的,說明兩個字符串匹配,反之,若是哪一個位置上,一個字符串發現已經有這個key值了,另外一個string卻發現hashmap裏並無重複出現的key值,說明兩個字符串的格式並不匹配。代碼以下:
class Solution { public boolean wordPattern(String pattern, String str) { String[]words = str.split(" "); if(pattern.length() != words.length) return false; Map map1=new HashMap(); Map map2=new HashMap(); for(int i = 0; i < pattern.length(); i++){ if((map1.put(pattern.charAt(i), i)) != map2.put(words[i], i)) return false; } return true; } }
因爲此題把第二個字符串轉化爲了字符數組,那麼遍歷時及時字符和字符串內容相同,其類型也不相同,因此能夠只用一個map。代碼進一步化簡爲:
1 class Solution { 2 public boolean wordPattern(String pattern, String str) { 3 String[] words = str.split(" "); 4 if (words.length != pattern.length()) 5 return false; 6 Map index = new HashMap(); 7 for (Integer i = 0; i < words.length; ++i) 8 if (index.put(pattern.charAt(i), i) != index.put(words[i], i)) 9 return false; 10 return true; 11 } 12 }