Java 确定字符串是否具有所有唯一字符

Java 确定字符串是否具有所有唯一字符,java,arrays,algorithm,data-structures,Java,Arrays,Algorithm,Data Structures,这是从破解编码面试书 这些问题实现了一种算法来确定字符串是否具有所有唯一字符。如果…怎么办 您不能使用其他数据结构吗 我想知道下面的if语句中发生了什么?谁能给我解释一下吗 我在评论中留下了我对代码的理解。如果我错了,请纠正我 public class Uniquechar2 { public static boolean isUniqueChars2(String str) { // Create a new boolean array of 256 charact

这是从破解编码面试书

这些问题实现了一种算法来确定字符串是否具有所有唯一字符。如果…怎么办 您不能使用其他数据结构吗

我想知道下面的if语句中发生了什么?谁能给我解释一下吗

我在评论中留下了我对代码的理解。如果我错了,请纠正我

public class Uniquechar2 {

    public static boolean isUniqueChars2(String str) {
         // Create a new boolean array of 256 characters to account for basic a cii and extended ascii characters
         boolean[] charSet = new boolean[256];

         //iterate through the array
         for (int i = 0; i < str.length(); i++) {

             // Assign the value of current value of the iterator i to int variable val.So if we are looping through "hello"  at i = 0 the int value of 'h' will be assigned to val.Is that correct?

             int val = str.charAt(i);

             // Continuing from the example of loping throughout the string "hello" the if statement will see if 'h' is in charSet and since it will be there it will return false /is that what is happening?

             if (charSet[val]) {
                 return false;
             }
             // Is this the else statement? true will be assigned to charSet[h] in this case       
             charSet[val] = true;
         }
         // I dont understand why we are returning true at the end ?
         return true;
    }
公共类Uniquechar2{
公共静态布尔值isUniqueChars2(字符串str){
//创建一个包含256个字符的新布尔数组,以说明基本cii和扩展ascii字符
布尔[]字符集=新布尔[256];
//遍历数组
对于(int i=0;i
这是else语句吗

否,否则代码中将有一个
else
。但在这种情况下,
else
是不必要的,因为如果
char\u set[val]
为true,则由于
返回false;
指令,该方法的执行将立即停止

我不明白为什么我们最终会回到现实

由于未找到重复项,因此该方法必须返回true,以指示字符串由唯一字符组成。如果已找到重复项,则该方法将已在中返回

if (char_set[val]) {
    return false;
}
public静态布尔值isUniqueChars2(String str){
//创建一个256个字符的新布尔数组,以说明基本ascii字符和扩展ascii字符
布尔[]字符集=新布尔[256];
//遍历我们正在测试的字符串
对于(int i=0;i
我只需要使用regex,它只需要一行代码:

public static boolean isUniqueChars(String str) {
    return str.matches("((.)(?!.*?\\2))*");
}
分解正则表达式:

  • ()
    捕获每个字符
  • (?!.*?\\2)
    是对捕获组的反向引用的反向前瞻
这两个词合在一起意味着“一个在其自身之后不会再出现的角色”

  • (…)*
    以上表示其中0-n个

总之,它意味着“由字符串中稍后确实会重新出现的字符组成”,即唯一字符。

一行解决方案,无需任何额外的数据结构:

str.chars().distinct().count() == (int)str.length();

我缩进了代码。缩进后,更容易理解。下一次,你自己做。有超过256个不同的字符。@Alan你的意思是有超过256个ASCII字符吗?有128个ASCII字符。但是Java
字符串
不局限于该集。你应该用检查您的算法是否可以处理输入,如果不能,则抛出异常。为什么在语句charSet[val]=true中为charSet[val]赋值true?当我使用语句if(charSet[val]){return false;},charSet[val]迭代h时,在字符串“hello”中将为真,因为字符集数组中存在“h”,因此我们如何在此处检查重复。您能否用“hello”这样的示例演示我们如何在此处检查重复
if(字符集[23])
不测试字符集数组中是否有索引23。它测试字符集数组的索引23处的值是否为真。默认情况下,布尔数组的所有元素都为假。为什么要将整个内容包装在捕获组中?如何解释此“!str.matches(()((!!!。\\2))*””@需要围绕整个表达式创建一个组,这样我就可以对其应用
*
。它不需要是一个捕获的组,但正则表达式无论如何都很难阅读,添加
?:
会产生更多的正则表达式噪音这是一个很棒的解释!
str.chars().distinct().count() == (int)str.length();