这是破解编码面试手册
问题实现一种算法来确定字符串是否具有所有唯一字符。如果 你不能使用其他数据结构吗?
我想知道下面的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;
}
答案 0 :(得分: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;
}
答案 1 :(得分:4)
这是else语句
不,否则代码中会有else
。但在这种情况下,else
是不必要的,因为如果char_set[val]
为真,则由于return false;
指令,方法的执行会立即停止。
我不明白为什么我们最后会回归真实?
因为由于未找到重复项,因此该方法必须返回true以指示该字符串由唯一字符组成。如果找到重复,则该方法已经在
中返回if (char_set[val]) {
return false;
}
答案 2 :(得分:2)
我只使用正则表达式,它只需要一行代码:
public static boolean isUniqueChars(String str) {
return str.matches("((.)(?!.*?\\2))*");
}
打破正则表达式:
(.)
捕获每个角色(?!.*?\\2)
对于捕获的组这些意味着&#34;一个不会再出现的角色&#34;
(...)*
表示0-n 总而言之,它意味着&#34;由字符组成,这些字符稍后会在字符串&#34;中重新出现,即唯一字符。
答案 3 :(得分:0)
没有任何额外数据结构的单行解决方案:
str.chars().distinct().count() == (int)str.length();