+ 1

How to remove consecutive character from a string which exactly matches k as: "aaabaaa","aaab","abcd" or "aaaba" or "aaabaa

Here is my code: class RemoveCharacters { func removeKOccurrences(_ data: String, _ k: Int) -> String { let text = Array(data) // Get the length let n: Int = text.count if (n == 0 || k <= 0) { return " " } var result: String = "" // Use to count character frequency var count: [Int] = Array(repeating: 0, count: 256) var i: Int = 0 while (i < n { count[Int(UnicodeScalar(String(text[i]))!.value)] += 1 i += 1 } i = 0 while (i < n) { if (count[Int(UnicodeScalar(String(text[i]))!.value)] != k) { // Include the resultant character result = result + String(text[i]) } i += 1 } return result } } let task: RemoveCharacters = RemoveCharacters() var d = task.removeKOccurrences("aaabaaa", 1) print(d) //HERE IS THE TEST CASES: Test Cases: "aaabbbc", 3 => "c" "abbbcddfg", 1 => "bbbdd" "abcd", 2 => "abcd" "abcd", 1 => " " "aaabaaa", 3 => "b" "aaaab", 3 => "aaaab" "bbbaabb", 3 => aabb We need to verify all the cases but out of it 5th and 7th i am unable to verify so help me...m fresher in swift.

15th Feb 2022, 12:25 PM
sheshadrivendra mishra
sheshadrivendra mishra - avatar
2 Answers
0
See, your program just went above my mind šŸ˜… But the logic is simple 1. You have to input the String and value of k. Add a " " to the end of the string 2. Then you have to take another String variable, suppose New as null and an int variable count=1. 3. Then you run a loop from 1 till ( length of String-1).(use operator <=) 3.1. if(S[i-1]==S[i]) then increment count by 1 3.2. else 3.2.1. if(count != k) then add the substring of that String from (i-count) till i to the variable New 3.2.2. set count=1 4.(outside loop) if New != Null then print the value of variable New else print " "
16th Feb 2022, 4:30 AM
Adi Nath Bhawani
Adi Nath Bhawani - avatar
0
Ok.tnk u i'll try
16th Feb 2022, 4:36 AM
sheshadrivendra mishra
sheshadrivendra mishra - avatar