Remove duplicate characters from a String in Scala Using Set
This is the another approach using a mutable Set to keep track of duplicate characters.
Below is the code in Scala using set.
// Program to remove duplicate from string using set
//creating object
object Gfg {
//remove duplicate function
def removeDuplicates(str: String): String = {
val set = scala.collection.mutable.Set[Char]()
val result = new StringBuilder
for (char <- str) {
if (!set(char)) {
result += char
contain += char
}
}
result.toString
}
//Main Method
def main(args: Array[String]): Unit = {
val inputString = "hello"
val outputString = removeDuplicates(inputString)
println(outputString)
}
}
Output:
Explanation:
- First we will define a removeDuplicate Method
- Inside that method we will define a mutable set named set.
- We iterate over each character in the input string str.
- For each character, if it’s not already present in the set, we append it to the result string and add it to the set.
- At the end, we convert the result string builder to a regular string and return it.
- In main method we will call removeDuplicate Function and Print the Output.
Time Complexity: O(n)
Auxiliary Space: O(n)
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