我嘗試解決字符串是否為等值線圖如下:
我不知道為什麼我的代碼不起作用。請有人能幫忙解釋一下原因嗎?
等值線圖沒有連續或不連續的重複字母。
我曾嘗試: 1- 將字符串轉換為小寫並使其成為數組。2- 如果字符串為空,則創建一個 if 檢查以返回 true。3- 通過數組運行 for 循環並比較每個字母的 firstIndex 和 lastIndex。如果第一個實例和最後一個實例不相同,則字符串不能是等值線圖,因此返回 false。??
function isIsogram(str){
str = str.toLowerCase();
let text = str.split("");
if (text.length === 0) {
return true;
}
for (let i = 0; i < text.length; i++) {
if ( text.indexOf(text[i]) !== text.lastIndexOf(text[i]) ){
return false;
} else {
return true;
}
}
}
一個簡單的更改應該可以解決問題。您現有的函數只考慮第一個字符。然後這將跳過字符串中的任何重複字符,例如,它為 'abb' 返回 true,這當然是不正確的。
最好繼續到循環結束,只有在我們確定沒有重複字符時才返回 true。
function isIsogram(str){
str = str.toLowerCase();
let text = str.split("");
if (text.length === 0) {
return true;
}
for (let i = 0; i < text.length; i++) {
if (text.indexOf(text[i]) !== text.lastIndexOf(text[i]) ){
return false;
}
}
return true;
}
const testInputs = ['abb','aab','aba','abc','abcdz'];
testInputs.forEach(input => console.log(`isIsogram(${input}): ${isIsogram(input)}`));
這是另一個實現,使用 aSet()
來計算唯一字符。如果字符串沒有重複字符,則設置大小給出的唯一字符數應與輸入字符串長度相同。
function isIsogram(str){
return new Set(str).size === str.length;
}
const testInputs = ['abb','aab','aba','abc', 'abcdz'];
testInputs.forEach(input => console.log(`isIsogram(${input}): ${isIsogram(input)}`));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句