290. Word Pattern【LeetCode by java】

今天发现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 }
相关文章
相关标签/搜索