Naive Approach to remove duplicate characters from a String in Scala
In the brute force approach, we compare each character in the string with every other character to determine if it’s a duplicate.
Below is the code in Scala.
// Program to remove duplicate from string using scala
// Creating Object
object Gfg {
//Method to removeDuplicates
def removeDuplicates(str: String): String = {
var result = ""
for (char <- str) {
if (!result.contains(char)) {
result += char
}
}
result
}
// Main Method
def main(args: Array[String]): Unit = {
val inputString = "hello"
val outputString = removeDuplicates(inputString)
println(stringWithoutDuplicates)
}
}
Output
Explanation:
- First we will create a function removeDuplicates
- Inside this function we will took a empty var string.
- We iterate over each character in the input string str.
- For each character, we check if it exists in the result string. If it doesn’t, we append it to the result.
- Finally, we return the result string, which contains unique characters.
- In main method we will call the removeDuplicate Method and Print the Output.
Time Complexity : O(n2)
How to remove duplicate characters from a String in Scala?
In this article, we will learn how to remove duplicate characters from a string in Scala using different approaches. First, we will look through the Brute-Force Approach and then use different standard libraries.
Examples:
Input: String = “hello”
Output: heloInput: String = “Geeks”
Output: Geks
Contact Us