在Swift中使用for-in循环检查字符串中的重复字符

zdwk9cvp  于 2023-06-04  发布在  Swift
关注(0)|答案(9)|浏览(379)

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

fykwrbwg1#

您可以使用字符的索引:

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))")
lawou6xi

lawou6xi2#

我用了一个散列来做。不知道它有多快,但它不需要在我的情况下。(在我的例子中,我正在处理电话号码,所以我先去掉破折号)

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
zu0ti5jz

zu0ti5jz3#

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

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

iqih9akk

iqih9akk4#

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

p5fdfcr15#

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]

你可以找到任何值的字符多少次写在字符串对象。

rfbsl7qr

rfbsl7qr6#

这是我的解决方案

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

vxqlmq5t7#

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

}
7ivaypg9

7ivaypg98#

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
afdcj2ne

afdcj2ne9#

等值线图

等值线图是其中没有一个字母重复的单词/短语,即所有字母都是唯一的。下面的算法比较小写字符,忽略单词之间的空格。
下面是我的代码:

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

相关问题