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:
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.思路:
(1)題意為給定一種字符樣式和一個字符串,要求判斷該字符串是否為給定的樣式。
(2)由於給定的pattern由若干字符組成,不同的字符應該對應不同的字符串,而相同的字符應該對應相同的字符串。這樣,可以通過Map對其進行實現。首先,將pattern轉化為字符數組pt,將待判斷的字符串轉為字符串數組split;其次,如果兩個數組的長度不等,則匹配失敗;否則,遍歷字符數組pt,如果當前字符在Map不存有,則判斷待判斷的字符串數組split在對應位置的值是否存於Map對應的Value中,如果存有,則匹配失敗,否則,將當前位置對應的字符和字符串存入Map中;如果當前遍歷的字符在Map對應的key中存有,判斷key對應的value是否為空,如果不為空,則判斷當前的value值和split對應的值是否相等,相等則繼續,否則匹配失敗;如果遍歷的字符在Map對應的key中不存有,則判斷value中是否存有split對應的值,如果有則匹配失敗,否則將當前key和value加入Map中。
(3)詳情見下方代碼。希望本文對你有所幫助。
import java.util.HashMap; import java.util.Map; public class Word_Pattern { public static void main(String[] args) { System.err.println(wordPattern(abba, dog dog dog dog)); } public static boolean wordPattern(String pattern, String str) { char[] pt = pattern.toCharArray(); String[] split = str.split( ); if (pt.length != split.length) return false; Mapmap = new HashMap (); for (int i = 0; i < pt.length; i++) { if (!map.containsKey(pt[i])) { if (map.values().contains(split[i])) { return false; } else { map.put(pt[i], split[i]); } } else { if (map.get(pt[i]) != null) { if (map.get(pt[i]).equals(split[i])) { continue; } else { return false; } } else { if (map.values().contains(split[i])) { return false; } else { map.put(pt[i], split[i]); } } } } return true; } }