确定字符串是否包含所有唯一字符

Sam*_*Lot 2 java arrays algorithm data-structures

这是破解编码面试书

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

我想知道下面的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;
    }
Run Code Online (Sandbox Code Playgroud)

Pet*_*nak 7

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

     // Iterate through the string we are testing
     for (int i = 0; i < str.length(); i++) {

         // Get the numerical (ascii) value of the character in the `str` at position `i`.
         int val = str.charAt(i);

         // If char_set[val] has been set, that means that this character was already present in the string. (so in string 'hello' this would be true for the second 'l')
         if (char_set[val]) {
             return false;
         }
         // If the character hasn't been encountered yet (otherwise we would have returned false above), then mark this particular character as present in the string
         char_set[val] = true;
     }
     // If the function hasn't returned false after going through the entire string that means that each character is unique - thus returning true
     return true;
}
Run Code Online (Sandbox Code Playgroud)