Reputation: 1638
Solved! Solution at the bottom.
I'm porting some Java code to Scala for fun and I trapped into a pretty nifty way of bit-shifting in Java. The Java code below takes a String as input and tests if it consists of unique characters.
public static boolean isUniqueChars(String str) {
if (str.length() > 256)return false; }
int checker = 0;
for (int i = 0; i < str.length(); i++) {
int val = str.charAt(i) - 'a';
if ((checker & (1 << val)) > 0) return false;
checker |= (1 << val);
}
return true;
Full listing is here: https://github.com/marvin-hansen/ctci/blob/master/java/Chapter%201/Question1_1/Question.java
How the code exactly works is explained here: How does this Java code which determines whether a String contains all unique characters work?
Porting this directly to Scala doesn't really work so I'm looking for a more functional way to re-write the stuff above.
I have tried BigInt & BitSet
def isUniqueChars2(str : String) : Boolean =
// Java, char's are Unicode so there are 32768 values
if (str.length() > 32768) false
val checker = BigInt(1)
for(i <- 0 to str.length){
val value = str.charAt(i)
if(checker.testBit(value)) false
checker.setBit(value)
}
true
}
This works, however, but without bit-shifting and without lowercase assumption. Performance is rather unknown ....
However, I would like to do a more functional style solution.
Thanks to user3189923 for the solution.
def isUniqueChars(str : String) = str.distinct == str
That's it. Thank you.
Upvotes: 1
Views: 519
Reputation: 20405
str.distinct == str
In general, method distinct
preserves order of occurrence after removing duplicates. Consider
implicit class RichUnique(val str: String) extends AnyVal {
def isUniqueChars() = str.distinct == str
}
and so
"abc".isUniqueChars
res: Boolean = true
"abcc".isUniqueChars
res: Boolean = false
Upvotes: 2