'Check for duplicate characters in string using for-loops in swift

I did this using while loops but I'm wondering if there's a way to do this with for loops. I'm trying to write this clean so I can write it on a whiteboard for people to understand.

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


Solution 1:[1]

Here is the for-loop version of your question.

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

There are a lot of ways this can be achieved and this is just one way of doing it.

Solution 2:[2]

You can use the indices of the characters:

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

Solution 3:[3]

I used a hash to do it. Not sure how fast it is but it doesn't need to be in my case. (In my case I'm doing phone numbers so I get rid of the dashes first)

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

... or more compact, as an extension...

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

Solution 4:[4]

As @adev said, there are many ways to finish this. For example, you can use only one for-loop with a dictionary to check the string is unique or not:

Time complexity: O(n). Required O(n) additional storage space for the dictionary.

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

Solution 5:[5]

this is my solution

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

Solution 6:[6]

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]

You can find any value of char how many times write in string object.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 adev
Solution 2
Solution 3 garafajon
Solution 4 bubuxu
Solution 5 cmaroney
Solution 6 yasin89