[英]Determine if a string has all unique characters
這是破解編碼面試書
問題 實現一個算法來確定一個字符串是否包含所有唯一的字符。 如果不能使用額外的數據結構怎么辦?
我想知道下面的 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;
}
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;
}
這是 else 語句嗎
不,否則代碼中會有一個else
。 但在這種情況下, else
是不必要的,因為如果char_set[val]
為真,方法的執行會立即停止,因為return false;
操作說明。
我不明白為什么我們最后返回 true ?
因為沒有找到重復項,該方法必須返回 true 以指示該字符串由唯一字符組成。 如果找到重復項,該方法將在
if (char_set[val]) {
return false;
}
我只會使用正則表達式,它只需要一行代碼:
public static boolean isUniqueChars(String str) {
return str.matches("((.)(?!.*?\\2))*");
}
分解正則表達式:
(.)
捕獲每個字符(?!.*?\\\\2)
是對捕獲組的反向引用的負面展望總之,這些意味着“一個不會再出現的角色”
(...)*
上面的意思是其中的 0-n 個總而言之,它的意思是“由稍后在字符串中重新出現的字符組成”,即獨特的字符。
沒有任何額外數據結構的單行解決方案:
str.chars().distinct().count() == (int)str.length();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.