使用Swift中的for-in循环来检查字符串中是否有重复字符。

5

我用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))")

3
这不是关于for循环的问题,但一个简单而有效的方法是检查Set(str.characters).count == str.characters.count - Martin R
9个回答

4
您可以使用字符的索引:
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))")

2
稍微简单一些:str.characters.indices.suffix(from: str.index(after: firstIndex)) 或者 str.characters.indices.suffix(from: firstIndex).dropFirst() - Martin R
好建议。我不知道索引。比我的答案好。你也得到了我的投票。 - adev
直到我开始寻找这个问题的好答案,我也不知道。 - Guy Kogus

3

我使用哈希(hash)来实现。不确定速度有多快,但在我的情况下并不需要很快。(我的情况是处理电话号码,所以我先去掉了破折号)

            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

2
这是你问题的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"
}

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


1
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]

你可以找到字符串对象中任何字符的出现次数。

1

正如 @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

0
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)
    }

}

目前你的回答不够清晰,请编辑并添加更多细节,以帮助其他人理解它如何回答问题。你可以在帮助中心找到有关如何编写好答案的更多信息。 - Community

0
let inputStr = "sakkett"
var tempStr = String()

for char in inputStr
{
    if tempStr.contains(char) == false
    {
        tempStr = tempStr.appending(String(char))

        let filterArr = inputStr.filter({ $0 == char})
        if filterArr.count > 1 {
            print("Duplicate char is \(char)")
        }
    }
}

//Output:
Duplicate char is k
Duplicate char is t

你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心找到有关如何编写良好答案的更多信息。 - Community

0

这是我的解决方案

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

0

同字母词

同字母词是指没有任何一个字母重复出现的单词或短语,即所有字母都是唯一的。下面的算法会将小写字母进行比较,并忽略单词之间的空格。

这是我的代码:

func isThisIsogram(_ string: String) -> Bool {
    var str = string.lowercased()
    str.replace(" ", with: "")
    let characters = Set<Character>(str)
    
    for char in characters {
        switch str.filter({ $0 == char }).count {
            case 2... : return false
            default   : continue
        }
    }
    return true
}

isThisIsogram("private logs")                // true
isThisIsogram("tomorrow morning")            // false
isThisIsogram("   ‍️")                 // true
isThisIsogram("γράμματα")                    // false
isThisIsogram("我 你 她")                     // true

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接