来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/word-pattern
题目
给定一种规律 pattern 和一个字符串 str ,判断 str 是否遵循相同的规律。
这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应规律。
示例1:
输入: pattern = "abba", str = "dog cat cat dog"
输出: true
示例 2:
输入:pattern = "abba", str = "dog cat cat fish"
输出: false
示例 3:
输入: pattern = "aaaa", str = "dog cat cat dog"
输出: false
示例 4:
输入: pattern = "abba", str = "dog dog dog dog"
输出: false
说明:
你可以假设 pattern 只包含小写字母, str 包含了由单个空格分隔的小写字母。
pattern 是类型,abba型,或者aaaa型(四个都一样)。str是要判断类型的字符串
方法
func wordPattern(_ pattern: String, _ str: String) -> Bool {
var result = true
if pattern.count <= 0 || str.count <= 0{
return false
}
var strArr = str.components(separatedBy: " ")
if strArr.count != pattern.count {
return false
}
var lastStr = pattern.first ?? Character("")
var index = 0
var resultDic = [Character: String]()
for character in pattern {
if index == strArr.count {
result = false
break
}
if index == 0 {
lastStr = character
resultDic[character] = strArr[index]
}else {
//判断数组上个和本次相等不
if lastStr == character {
//如果两个值是否不相等
if resultDic[character] != strArr[index] {
result = false
break
}
}else {
//判断是不是相等
if resultDic.keys.contains(character) {
if resultDic[character] != strArr[index] {
result = false
break
}
}else {
resultDic[character] = strArr[index]
}
if strArr[index] == strArr[index - 1] {
result = false
break
}
}
lastStr = character
}
index += 1
}
return result
}
注意,aaa , dog dog dog dog。这种的也是return false
网友评论