★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-rglbkycb-kw.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given a pattern
and a string str
, find if str
follows the same pattern.git
Here follow means a full match, such that there is a bijection between a letter in pattern
and a non-empty substring in str
.github
Example 1:微信
Input: pattern = , str = Output: true"abab""redblueredblue"
Example 2:測試
Input: pattern = , str = Output: true"aaaa""asdasdasdasd"
Example 3:spa
Input: pattern = , str = Output: false "aabb""xyzabcxzyabc"
Notes:
You may assume both pattern
and str
contains only lowercase letters.code
給定一個模式和一個字符串str,找出str是否遵循相同的模式。htm
這裏follow意味着徹底匹配,這樣在模式中的字母和str中的非空子字符串之間就有一個雙射。blog
例1:索引
輸入:pattern=「abab」,str=「redblueredblue」
輸出:true
例2:
輸入:pattern=「aaaa」,str=「asdasdasd」
輸出:true
例3:
輸入:pattern=「aabb」,str=「xyzabcxzyabc」
輸出:false
注意:
您能夠假定pattern和str都只包含小寫字母。
Solution:
1 class Solution { 2 var m:[Character:String] = [Character:String]() 3 var s:Set<String> = Set<String>() 4 func wordPatternMatch(_ pattern:String,_ str:String) -> Bool { 5 if pattern.isEmpty {return str.isEmpty} 6 var arrChar:[Character] = Array( pattern) 7 if m[arrChar[0]] != nil 8 { 9 var t:String = m[arrChar[0]]! 10 if t.count > str.count || str.subString(0, t.count) != t 11 { 12 return false 13 } 14 if wordPatternMatch(pattern.subString(1), str.subString(t.count)) 15 { 16 return true 17 } 18 } 19 else 20 { 21 for i in 1...str.count 22 { 23 if s.contains(str.subString(0, i)) {continue} 24 m[arrChar[0]] = str.subString(0, i) 25 s.insert(str.subString(0, i)) 26 if wordPatternMatch(pattern.subString(1), str.subString(i)) 27 { 28 return true 29 } 30 m[arrChar[0]] = nil 31 s.remove(str.subString(0, i)) 32 } 33 } 34 return false 35 } 36 } 37 38 extension String { 39 // 截取字符串:從index到結束處 40 // - Parameter index: 開始索引 41 // - Returns: 子字符串 42 func subString(_ index: Int) -> String { 43 let theIndex = self.index(self.endIndex, offsetBy: index - self.count) 44 return String(self[theIndex..<endIndex]) 45 } 46 47 // 截取字符串:指定索引和字符數 48 // - begin: 開始截取處索引 49 // - count: 截取的字符數量 50 func subString(_ begin:Int,_ count:Int) -> String { 51 let start = self.index(self.startIndex, offsetBy: max(0, begin)) 52 let end = self.index(self.startIndex, offsetBy: min(self.count, begin + count)) 53 return String(self[start..<end]) 54 } 55 }
點擊:Playground測試
1 print(Solution().wordPatternMatch("abab","redblueredblue")) 2 //Print true 3 print(Solution().wordPatternMatch("aaaa","asdasdasdasd")) 4 //Print true 5 print(Solution().wordPatternMatch("aabb","xyzabcxzyabc")) 6 //Print false