JavaScript中限制重複字元出現次數為一次
問題
我們需要編寫一個JavaScript函式,該函式只接收一個字串str作為引數。
該函式應根據輸入字串準備一個新的字串,其中每個字元只保留一個出現,保留的字元是使結果字串按字典順序最小的字元。
例如,如果函式的輸入是:
const str = 'cbacdcbc';
那麼輸出應該是:
const output = 'acdb';
輸出解釋
請注意,我們可以從字串中刪除任何“c”的出現,但是我們刪除了第一個“c”,這使得字串按字典順序最小,對於“a”和“b”也是如此。
示例
這段程式碼將是:
const str = 'cbacdcbc';
const removeDuplicates = (str = '') => {
if (str.length <= 1) {
return str;
};
let flag;
let string = "";
let legend = new Array(26).fill(-1 let last = "z";
let ind = 0;
for (let i = str.length - 1; i > -1; i--) {
const element = str[i];
if (legend[element.charCodeAt() - 97] < 0) {
legend[element.charCodeAt() - 97] = i;
last = element;
ind = i;
string += element;
} else {
if (last >= element) {
last = element;
ind = i;
}
}
}
let finalStr = last;
while (string.length > finalStr.length) {
legend.fill(-1);
for (let i = str.length - 1; i > ind; i--) {
const element = str[i];
if (finalStr.indexOf(element) < 0) {
if (legend[element.charCodeAt() - 97] < 0) {
legend[element.charCodeAt() - 97] = i;
last = element;
flag = i;
} else {
if (last >= element) {
last = element;
flag = i;
}
}
}
}
ind = flag;
finalStr += last;
}
return finalStr;
};
console.log(removeDuplicates(str));程式碼解釋
這裡的思路是:
首先,我們迴圈遍歷整個字串以檢查使用了哪些字母,並找到包含所有字元的最小起始字母子字串。
如果我們從右到左開始迴圈並記住子字串的起始位置和起始最小字母,則更容易理解。
然後,我們開始迴圈遍歷子字串(不包括起始最小字母),仍然是從右到左,但這次我們需要忽略我們已經儲存的字母。
輸出
控制檯中的輸出將是:
acdb
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP