在swift中使用for循环检查字符串中的重复字符

yc0p9oo0  于 2022-12-10  发布在  Swift
关注(0)|答案(7)|浏览(245)

我用while循环做了这个,但是我想知道是否有一种方法可以用for循环来做这个,我试着把这个写得干净,这样我就可以把它写在白板上,让人们理解。

var str = "Have a nice day"

func unique(_ str: String) -> String {
var firstIndex = str.startIndex

while (firstIndex != str.endIndex) {
    var secondIndex = str.index(after: firstIndex)
    while (secondIndex != str.endIndex) {
        if (str[firstIndex] == str[secondIndex]) {
            return "Not all characters are unique"
        }
        secondIndex = str.index(after: secondIndex)
    }
    firstIndex = str.index(after: firstIndex)
}
return "All the characters are unique"
}

print("\(unique(str))")
6pp0gazn

6pp0gazn1#

您可以使用字符的索引:

var str = "Have a nice day"

func unique(_ str: String) -> String {
    for firstIndex in str.characters.indices {
        for secondIndex in str.characters.indices.suffix(from: str.index(after: firstIndex)) {
            if (str[firstIndex] == str[secondIndex]) {
                return "Not all characters are unique"
            }
        }
    }
    return "All the characters are unique"
}

print("\(unique(str))")
o2rvlv0m

o2rvlv0m2#

我用了一个哈希函数。不知道它有多快,但在我的情况下不需要。(在我的情况下,我正在处理电话号码,所以我先去掉破折号)

let theLetters = t.components(separatedBy: "-")
            let justChars = theLetters.joined()
            var charsHash = [Character:Int]()
            justChars.forEach { charsHash[$0] = 1 }
            if charsHash.count < 2 { return false }

...或更紧凑,作为扩展...

extension String {
    var isMonotonous: Bool {
        var hash = [Character:Int]()
        self.forEach { hash[$0] = 1 }
        return hash.count < 2
    }
}

let a = "asdfasf".isMonotonous   // false
let b = "aaaaaaa".isMonotonous   // true
puruo6ea

puruo6ea3#

下面是你的问题的for循环版本。

let string = "Have a nice day"

func unique(_ string: String) -> String {
    for i in 0..<string.characters.count {
        for j in (i+1)..<string.characters.count {
            let firstIndex = string.index(string.startIndex, offsetBy: i)
            let secondIndex = string.index(string.startIndex, offsetBy: j)
            if (string[firstIndex] == string[secondIndex]) {
                return "Not all characters are unique"
            }
        }
    }
    return "All the characters are unique"
}

有很多方法可以实现这一点,这只是其中一种方法。

30byixjq

30byixjq4#

正如@adev所说,有很多方法可以完成这一步,比如,你可以只使用一个for循环和一个字典来检查字符串是否是唯一的:

  • 时间复杂度:时间复杂度为O(n),因此,时间复杂度为O(n)。
func unique(_ input: String) -> Bool {

    var dict: [Character: Int] = [:]

    for (index, char) in input.enumerated() {
        if dict[char] != nil { return false }
        dict[char] = index
    }

    return true

}

unique("Have a nice day") // Return false
unique("Have A_nicE-dⒶy") // Return true
jfgube3f

jfgube3f5#

let str = "Hello I m sowftware developer"
var dict : [Character : Int] = [:]

let newstr = str.replacingOccurrences(of: " ", with: "")
print(newstr.utf16.count)

for i in newstr {
    if dict[i] == nil {
        dict[i] = 1
    }else{
        dict[i]! += 1
    }
}

print(dict) // ["e": 5, "v": 1, "d": 1, "H": 1, "f": 1, "w": 2, "s": 1, "I": 1, "m": 1, "o": 3, "l": 3, "a": 1, "r": 2, "p": 1, "t": 1]

你可以在字符串对象中找到任意值char的多少次写入。

bmvo0sr5

bmvo0sr56#

这是我解决方案

func hasDups(_ input: String) -> Bool {
    for c in input {
        if (input.firstIndex(of: c) != input.lastIndex(of: c)) {
            return true
        }
    }
    return false
}
vwhgwdsa

vwhgwdsa7#

let input = "ssaajaaan"
var count = 1
for i in 0..<input.count
{
   let first = input[input.index(input.startIndex, offsetBy: i)]
    if i + 1 < input.count
    {
let next = input[input.index(input.startIndex, offsetBy: i + 1)]
        if first == next
        {
            count += 1
        }
        else
        {
            count = 1
        }
    }
    if count >= 2
    {
        print(first," = ",count)
    }

}

相关问题