★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10692315.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
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 substring in str
.
Example 1:
Input: pattern ="abab"
, str ="redblueredblue"
Output: true
Example 2:
Input: pattern ="aaaa"
, str ="asdasdasdasd"
Output: true
Example 3:
Input: pattern ="aabb"
, str ="xyzabcxzyabc"
Output: false
Notes:
You may assume both pattern
and str
contains only lowercase letters.
给定一个模式和一个字符串str,找出str是否遵循相同的模式。
这里follow意味着完全匹配,这样在模式中的字母和str中的非空子字符串之间就有一个双射。
例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