I wrote a method that removes all 2 duplicate characters in String, for example
I need delete only char that contains twice, for example
"bndkss" -> "bndk"
"nnmmhj" - > "hj"
"aaabbaac" -> "ac
"abba" -> ""
I wrote on objc and everything works, but Swift is not working, help please, where did I go wrong?
override func viewDidLoad() {
super.viewDidLoad()
let string = "baab"
print("before: \(string)")
let stringAfter = checkString(string: string)
print("after: \(stringAfter)")
}
func checkString(string : String) -> String {
var tempString = string
for (index, element) in string.characters.enumerated() {
for (index2, element2) in string.characters.enumerated() {
if element == element2 && index != index2 {
if index > index2 {
tempString.remove(at: tempString.index(tempString.startIndex, offsetBy: index))
tempString.remove(at: tempString.index(tempString.startIndex, offsetBy: index2))
} else {
tempString.remove(at: tempString.index(tempString.startIndex, offsetBy: index2))
tempString.remove(at: tempString.index(tempString.startIndex, offsetBy: index))
}
if tempString.characters.count < 1 {
return ""
} else {
checkString(string: tempString)
}
} else {
if index == tempString.characters.count - 1 && index2 == tempString.characters.count - 1 {
return tempString
}
}
}
}
return ""
}
Updates:
just need
return checkString(string: tempString)
instead
checkString(string: tempString)
There are two problems in your code, such as
After removing characters in tempString, the indices index and index2 to long refer to the original characters in tempString.
Wrong characters are removed as a consequence.
You call checkString() recursively but discard the result.
Update: As you already noticed in the meantime, return checkString(string: tempString) solves these problems.
Here is an alternative implementation. The idea is to use a dictionary
to remember where a character has been seen last, and an index set
which keeps track of the positions of the characters which are to
be preserved. Instead of two nested loops and recursion, two "simple"
loops are used here, plus the cost of the dictionary and set operations.
func removeDuplicateCharacters(string: String) -> String {
var seen = [Character: Int]()
var keep = IndexSet(integersIn: 0..<string.characters.count)
for (idx, c) in string.characters.enumerated() {
if let prevIndex = seen[c] {
keep.remove(prevIndex)
keep.remove(idx)
seen.removeValue(forKey: c)
} else {
seen[c] = idx
}
}
return String(keep.map { string[string.index(string.startIndex, offsetBy: $0)] })
}
Examples:
print(removeDuplicateCharacters(string: "bndkss")) // ""bndk"
print(removeDuplicateCharacters(string: "nnmmhj")) // "jh"
print(removeDuplicateCharacters(string: "abba")) // ""
print(removeDuplicateCharacters(string: "aaabbaac")) // "ac"
Martin wrote a much cleaner version than myself, but I worked on this for a little while so I figured I'd post it to show you another way it could have been accomplished.
func removeDuplicates(from original: String) -> String {
var originalString = original
var newString = ""
for character in originalString.characters {
if !newString.contains("\(character)") {
newString.append(character)
originalString = originalString.characters.filter { $0.description != "\(character)" }.map { "\($0)" }.joined(separator: "")
} else {
newString = newString.characters.filter { $0.description != "\(character)" }.map { "\($0)" }.joined(separator: "")
}
}
return newString
}
Related
I'm having this issue of trying to trying to recursively print out all subsets of the giving array of String(characters) using swift. The value is ("a1b2"). The output should have 4 subsets.
Currently stuck here:
func overall(string: String) {
helper(string: string, i: 0, slate: "")
}
func helper(string: String, i: Int, slate: String) {
var result = [Any]()
let word = Array(string)
var counter = i
if string.count == counter {
result.append(slate)
} else {
if word[i].isNumber {
counter += 1
helper(string: string, i: counter, slate: slate + String(word[i]))
} else if word[i].isLowercase {
counter += 1
helper(string: string, i: counter, slate: slate + String(word[i]).uppercased())
} else {
counter += 1
helper(string: string, i: counter, slate: slate + String(word[i]).lowercased())
}
}
}
overall(string: "a1b2")
I'm having issues creating a base case in the helper functions. Also I'm unsure if I'm using recursion properly. Could you please help with an explanation, it will be greatly appreciated.
I'm sure this is totally useless in general, but just for fun, here's an amusing recursion-free solution for the particular problem given, where we know the string is exactly four characters and we know that either uppercased or lowercased must be applied to each character:
let s = "a1b2"
let arr = Array(s).map(String.init)
var result : Set<String> = []
for i in 0b0000...0b1111 {
var tog = [Bool]()
for sh in 0...3 { tog.append(i & 1<<sh == 0) }
var word = ""
for ix in 0...3 {
let f = tog[ix] ? arr[ix].lowercased : arr[ix].uppercased
word = word + f()
}
result.insert(word)
}
print(result)
The OP clarified in comments that he wanted the case-variants of the original string, not "subsets" as originally stated
[Edit] I originally had a paragraph here about String.count, however, my memory must have been in error, because Apple's documentation does state that String.count is in fact the number of Characters, which is what we would all want it to be anyway. I hope my error didn't throw anyone too far off.
You don't need any counters. All you need is the first character, and recurse on the rest of the string.
The thing is, when you have a letter as your first you need to preprend both the upper and lower case variants to all of the strings returned by the recursive call.
The base case is at the end of the string, in which case you return an an array containing just the empty string.
Here's my implementation:
func caseVariants(of s: String) -> [String]
{
func caseVariants(of s: Substring) -> [String]
{
guard let c = s.first else { return [""] } // base case
let remainder = s[s.index(after: s.startIndex)...]
let remainderVariants = caseVariants(of: remainder)
var results: [String] = []
if c.isLetter
{
results.append(
contentsOf: remainderVariants.map {
"\(c.uppercased())" + $0
}
)
results.append(
contentsOf: remainderVariants.map {
"\(c.lowercased())" + $0
}
)
}
else
{
results.append(
contentsOf: remainderVariants.map { "\(c)" + $0 }
)
}
return results
}
return caseVariants(of: s[...]).sorted()
}
print("Case variants:")
for s in caseVariants(of: "a1b2") { print("\"\(s)\"") }
The output is:
Case variants:
"A1B2"
"A1b2"
"a1B2"
"a1b2"
[EDIT] in comments, OP asked what if .startIndex were disallowed (such as in an interview). While I think such a restriction is insane, there is an easy solution, and it's a one-line, quite reasonable change to my previous code. Change this line:
let remainder = s[s.index(after: s.startIndex)...]
to use .dropFirst()
let remainder = s.dropFirst()
If we look at the implementation of dropFirst in the Collection protocol in the standard library:
#inlinable
public __consuming func dropFirst(_ k: Int = 1) -> SubSequence {
_precondition(k >= 0, "Can't drop a negative number of elements from a collection")
let start = index(startIndex, offsetBy: k, limitedBy: endIndex) ?? endIndex
return self[start..<endIndex]
}
We see that the use of dropFirst will use the default value of 1 for k. In that case, when we've already checked that we're not at the end of the string, the line
let start = index(startIndex, offsetBy: k, limitedBy: endIndex) ?? endIndex
is equivalent to
let start = index(after: startIndex)
which means that the returned substring is
return self[index(after: startIndex)..<endIndex]
which is just the canonical way of saying:
return self[index(after: startIndex)...]
So a version using dropFirst() is identical to the original solution once inlining has done its thing.
I want to create a function where an input of a string is taken in and the output returns a string of how many times the number is repeated. For example if my string is "1111223444" it will return "41221334", because there are four 1's, two 2's, one 3, and three 4's. So an input of "2234467" would return "2213241617". I am not sure if a dictionary would be the best way to implement it and I am really confused. I have started the function however don't know where to go from here. Any tips or resources will be helpful.
func stringOutput(input: String) -> String {
var result = ""
var lastCharacter: Character
var count = 0
var countDict: [String: Int] = [:]
for item in input {
countDict[item] as Character
}
return result
}
Your function computes the next term of the Look-and-say sequence. Here is an implementation (essentially taken from Leetcode 38: The โcount-and-sayโ sequence on Code Review). Instead of traversing the string, we directly search for the next index of a character different from the current one. Neither the first nor the last run has be be treated specially:
extension String {
func lookAndSay() -> String {
var result = ""
var fromIndex = startIndex // Start of current run
while fromIndex != endIndex {
let char = self[fromIndex] // Current character
// Find start of next run
let toIndex = self[fromIndex...].firstIndex(where: { $0 != char }) ?? endIndex
// Compute length of run, and append it to the result
let len = distance(from: fromIndex, to: toIndex)
result += "\(len)\(char)"
// Continue with next run
fromIndex = toIndex
}
return result
}
}
print("1111223444".lookAndSay()) // 41221334
print("2234467".lookAndSay()) // 2213241617
Try the snippet below.
func stringOutput(input: String) -> String {
var result = ""
var lastKnownCharacter: Character? = nil
var lastKnownCharacterCount: Int = 0
for character in input {
if lastKnownCharacter == nil {
lastKnownCharacter = character
lastKnownCharacterCount = 1
} else if lastKnownCharacter == character {
lastKnownCharacterCount += 1
} else {
result.append("\(lastKnownCharacterCount)\(lastKnownCharacter!)")
lastKnownCharacter = character
lastKnownCharacterCount = 1
}
}
result.append("\(lastKnownCharacterCount)\(lastKnownCharacter!)")
return result
}
I am trying to solve the Palindrome Partitioning Question. You can find the question in https://leetcode.com/problems/palindrome-partitioning/.
And I came up with the solution:
func partition(_ s: String) -> [[String]] {
var result: [[String]] = []
func dfs(string: String, partiton: [String]) {
if string.characters.count == 0 {
result.append(partiton)
return
}
for length in 1...string.characters.count {
let endIndex = string.index(string.startIndex, offsetBy: length-1)
let part = string[string.startIndex...endIndex]
if isPalindrome(part) {
let leftPart = string[string.index(after: endIndex)..<string.endIndex]
print("string: \(string) part: \(part) leftpart: \(leftPart)")
dfs(string: leftPart, partiton: partiton + [part])
}
}
}
func isPalindrome(_ s: String) -> Bool {
if String(s.characters.reversed()) == s {
return true
} else {
return false
}
}
dfs(string: s, partiton: [])
return result
}
But the performance is Bad. Time Limit Exceeded.
But the same idea with Python implementation can pass:
def partition(self, s):
res = []
self.dfs(s, [], res)
return res
def dfs(self, s, path, res):
if not s:
res.append(path)
return
for i in range(1, len(s)+1):
if self.isPal(s[:i]):
self.dfs(s[i:], path+[s[:i]], res)
def isPal(self, s):
return s == s[::-1]
It make me wonder that how to improve the swift implementation and why the swift implementation is slower than python.
A Swift String is a collection of Characters, and a Character represents a single extended grapheme cluster, that can be one or more
Unicode scalars. That makes some index operations like "skip the first N characters" slow.
But the first improvement is to "short-circuit" the isPalindrome()
function. Instead of building the reversed string completely, compare
the character sequence with its reversed sequence and stop as soon
as a difference is found:
func isPalindrome(_ s: String) -> Bool {
return !zip(s.characters, s.characters.reversed()).contains { $0 != $1 }
}
s.characters.reversed() does not create a new collection in reverse
order, it just enumerates the characters from back to front.
With String(s.characters.reversed()) as in your method however,
you force the creation of a new collection for the reversed string,
that makes it slow.
For the 110-character string
let string = String(repeating: "Hello world", count: 10)
this reduces the computation time from about 6 sec to 1.2 sec in my test.
Next, avoid index calculations like
let endIndex = string.index(string.startIndex, offsetBy: length-1)
and iterate over the character index itself instead:
func partition(_ s: String) -> [[String]] {
var result: [[String]] = []
func dfs(string: String, partiton: [String]) {
if string.isEmpty {
result.append(partiton)
return
}
var idx = string.startIndex
repeat {
string.characters.formIndex(after: &idx)
let part = string.substring(to: idx)
if isPalindrome(part) {
let leftPart = string.substring(from: idx)
dfs(string: leftPart, partiton: partiton + [part])
}
} while idx != string.endIndex
}
func isPalindrome(_ s: String) -> Bool {
return !zip(s.characters, s.characters.reversed()).contains { $0 != $1 }
}
dfs(string: s, partiton: [])
return result
}
Computation time is now 0.7 sec.
The next step is to avoid string indexing totally, and work with
an array of characters, because array indexing is fast. Even better,
use array slices which are fast to create and reference the original
array elements:
func partition(_ s: String) -> [[String]] {
var result: [[String]] = []
func dfs(chars: ArraySlice<Character>, partiton: [String]) {
if chars.isEmpty {
result.append(partiton)
return
}
for length in 1...chars.count {
let part = chars.prefix(length)
if isPalindrome(part) {
let leftPart = chars.dropFirst(length)
dfs(chars: leftPart, partiton: partiton + [String(part)])
}
}
}
func isPalindrome(_ c: ArraySlice<Character>) -> Bool {
return !zip(c, c.reversed()).contains { $0 != $1 }
}
dfs(chars: ArraySlice(s.characters), partiton: [])
return result
}
Computation time is now 0.08 sec.
If your string contains only characters in the "basic multilingual plane" (i.e. <= U+FFFF) then you can work with UTF-16 code points instead:
func partition(_ s: String) -> [[String]] {
var result: [[String]] = []
func dfs(chars: ArraySlice<UInt16>, partiton: [String]) {
if chars.isEmpty {
result.append(partiton)
return
}
for length in 1...chars.count {
let part = chars.prefix(length)
if isPalindrome(part) {
let leftPart = chars.dropFirst(length)
part.withUnsafeBufferPointer {
dfs(chars: leftPart, partiton: partiton + [String(utf16CodeUnits: $0.baseAddress!, count: length)])
}
}
}
}
func isPalindrome(_ c: ArraySlice<UInt16>) -> Bool {
return !zip(c, c.reversed()).contains { $0 != $1 }
}
dfs(chars: ArraySlice(s.utf16), partiton: [])
return result
}
Computation time is now 0.04 sec for the 110 character test string.
So some tips which potentially can improve the performance when working with Swift strings are
Iterate over the characters/indices sequentially. Avoid "jumping"
to the n'th position.
If you need "random" access to all characters, convert the string
to an array first.
Working with the UTF-16 view of a string can be faster than working
with the characters view.
Of course it depends on the actual use-case. In this application,
we were able to reduce the computation time from 6 sec to 0.04 sec,
that is a factor of 150.
I'm trying to implement KSTokenView in my Swift 2 project. I have fixed all of the small errors in the conversion, but I have three instances of the same error that I can't figure out how to fix. The issue is with the advance method and I am getting a compile time error that says 'advance is unavailable: call the advancedBy(n)' method on the index. I've tried to look at another answer involving this method but after struggling for a while I can't figure it out.
The problem code is:
First instance is in the method below, I will mark it with a comment
private func _updateText() {
if (!_setupCompleted) {return}
_initPlaceholderLabel()
switch(_state) {
case .Opened:
text = KSTextEmpty
break
case .Closed:
if tokens.count == 0 {
text = KSTextEmpty
} else {
var title = KSTextEmpty
for token: KSToken in tokens {
title += "\(token.title)\(_separatorText!)"
}
if (title.characters.count > 0) {
//advance call made in the statement below
title = title.substringWithRange(Range<String.Index>(start: advance(title.startIndex, 0), end: advance(title.endIndex, -_separatorText!.characters.count)))
}
let width = KSUtils.widthOfString(title, font: font!)
if width + _leftViewRect().width > bounds.width {
text = "\(tokens.count) \(_descriptionText)"
} else {
text = title
}
}
break
}
_updatePlaceHolderVisibility()
}
Second and third instances are in this function called textField:shouldChangeCharactersInRange in the if statement if(string.isEmpty). I will also mark the if statement and the two advance method calls.
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// If backspace is pressed
if (_tokenField.tokens.count > 0 && _tokenField.text == KSTextEmpty && string.isEmpty == true && shouldDeleteTokenOnBackspace) {
if (_lastToken() != nil) {
if (selectedToken() != nil) {
deleteSelectedToken()
} else {
_tokenField.selectToken(_lastToken()!)
}
}
return false
}
// Prevent removing KSEmptyString
if (string.isEmpty == true && _tokenField.text == KSTextEmpty) {
return false
}
var searchString: String
let olderText = _tokenField.text
// Check if character is removed at some index
// Remove character at that index
if (string.isEmpty) { //advance calls are made in this if statement
let first: String = olderText!.substringToIndex(advance(olderText!.startIndex, range.location)) as String // advance called here (1/2)
let second: String = olderText!.substringFromIndex(advance(olderText!.startIndex, range.location+1)) as String // advance called here (2/2)
searchString = first + second
} else { // new character added
if (tokenizingCharacters.contains(string) && olderText != KSTextEmpty && olderText!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) != "") {
addTokenWithTitle(olderText!, tokenObject: nil)
return false
}
searchString = olderText!+string
}
// Allow all other characters
if (searchString.characters.count >= minimumCharactersToSearch && searchString != "\n") {
_lastSearchString = searchString
startSearchWithString(_lastSearchString)
}
_tokenField.scrollViewScrollToEnd()
return true
}
Edit: Figured it out. Take the first parameter and call advancedBy(n) on it. Then put the second parameter in the 'n' slot.
Example: let second: String = olderText!.substringFromIndex(olderText!.startIndex.advancedBy(range.location+1)) as String
I know that there will be lots of pointers to duplicates but this worked before I updated to xcode 6.3 and now it has a problem with it.
The script:
extension String {
func removeCharsFromEnd(count:Int) -> String {
var getSelf = self as String
var stringLength = count(getSelf.utf16)
let substringIndex = (stringLength < count) ? 0 : stringLength - count
return self.substringToIndex(advance(self.startIndex, substringIndex))
}
}
Error : Cannot invoke 'count' with an argument of list of type '(String.UTF16View)'
I also want to point out that this new method for counting works everywhere else I have used out (outside of this extension).
Thanks in advance.
count is the name of your extension method parameter and hides the
Swift library function count(). You can rename the parameter
or call
var stringLength = Swift.count(getSelf.utf16)
explicitly.
But note that counting the number of UTF-16 code units is wrong here, it should be
var stringLength = Swift.count(getSelf)
to count the number of characters in the string, because that is what
advance() also counts. You can verify that easily with
let foo = "๐๐๐".removeCharsFromEnd(1)
println(foo)
Here is a simplified version of your method:
extension String {
func removeCharsFromEnd(count : Int) -> String {
precondition(count >= 0, "Attempt to call removeCharsFromEnd() with a negative count")
// Decrement `endIndex` by `count`, but not beyond `startIndex`:
let idx = advance(self.endIndex, -count, self.startIndex)
return self.substringToIndex(idx)
}
}
using the three-argument version of advance() with a negative distance.
Update for Swift 2/Xcode 7:
extension String {
func removeCharsFromEnd(count : Int) -> String {
precondition(count >= 0, "Attempt to call removeCharsFromEnd() with a negative count")
// Decrement `endIndex` by `count`, but not beyond `startIndex`:
let idx = self.endIndex.advancedBy(-count, limit: self.startIndex)
return self.substringToIndex(idx)
}
}
var str = "Hello, playground"
extension String {
func removeCharsFromEnd(n:Int) -> String {
return substringWithRange(Range(start: startIndex, end: advance(startIndex, count(self) < n ? 0 : count(self)-n )))
}
}
"Hello, playground".removeCharsFromEnd(3) // "Hello, playgro"
"๐๐๐".removeCharsFromEnd(1) // "๐๐"
you can also use subscript:
extension String {
subscript(index: Int) -> String? {
guard index >= 0 && index < characters.count else { return nil }
return String(self[startIndex.advancedBy(index)])
}
subscript(range: Range<Int>) -> String? {
guard
range.startIndex >= 0 &&
range.endIndex <= characters.count &&
startIndex.advancedBy(range.endIndex) <= endIndex &&
startIndex.advancedBy(range.startIndex) >= startIndex &&
range.startIndex.distanceTo(range.endIndex) <= characters.count
else { return nil }
return self[startIndex.advancedBy(range.startIndex)..<startIndex.advancedBy(range.endIndex)]
}
}
"Hello, playground"[0...4] // "Hello"
"Hello, playground"[5] // ","
"Hello, playground"[7...16] // "playground"
"๐๐๐"[1] // "๐"