Remove duplicate characters from a String in Scala Using Distinct Method
The distinct method provides a convenient way to remove duplicate characters from a string in Scala.
Below is the code of remove duplicate characters from a string using string.distinct Method.
// Creating Object
object Gfg {
// defining a removeDuplicate Method
def removeDuplicates(str: String): String = {
// Using string.distinct method
str.distinct
}
//defining main Method
def main(args: Array[String]): Unit = {
val inputString = "w3wiki"
val outputString = removeDuplicates(inputString)
println(outputString)
}
}
Output:
Explanation
- The removeDuplicates function simply calls the distinct method on the input string str, which returns a new string with duplicate characters removed.
- The main method is the entry point for the program.
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