【问题标题】:Scala: Function test a string for unique charScala:函数测试字符串的唯一字符
【发布时间】:2014-04-03 09:55:21
【问题描述】:

解决了!底部的解决方案。

为了好玩,我将一些 Java 代码移植到 Scala 中,但我陷入了一种非常漂亮的 Java 位移方式。下面的 Java 代码将 String 作为输入并测试它是否由唯一字符组成。

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;

完整列表在这里:https://github.com/marvin-hansen/ctci/blob/master/java/Chapter%201/Question1_1/Question.java

这里解释了代码的确切工作原理: How does this Java code which determines whether a String contains all unique characters work?

将其直接移植到 Scala 并没有真正起作用,因此我正在寻找一种更实用的方法来重写上面的内容。

我已经尝试过 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
}

然而,这可行,但没有位移,也没有小写假设。 性能相当未知....

但是,我想做一个更实用的风格解决方案。

感谢 user3189923 的解决方案。

 def isUniqueChars(str : String) = str.distinct == str

就是这样。谢谢你。

【问题讨论】:

    标签: java scala


    【解决方案1】:
    str.distinct == str
    

    通常,方法distinct 在删除重复项后保留出现顺序。考虑

    implicit class RichUnique(val str: String) extends AnyVal {
      def isUniqueChars() = str.distinct == str
    }
    

    等等

    "abc".isUniqueChars
    res: Boolean = true
    
    "abcc".isUniqueChars
    res: Boolean = false
    

    【讨论】:

    • 正要问。谢谢你的好主意,我不知道有什么不同
    【解决方案2】:

    怎么样:

    str.toSet.size == str.size
    

    ?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多