Last active
May 21, 2020 16:17
-
-
Save stevencch99/0c48e0340d582184adba9ee2c9db30b4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function primeString(s) { | |
// 將字串重複的部份切成一個規律的陣列 | |
let spArr = s.split(s[0]); | |
// 切掉不要的頭部空元素 | |
spArr.shift(); | |
// 宣告 不重複計數器 | |
let falseCount = 0; | |
// 將各個元素和它們出現的次數存成 key-value pair | |
let tCounter = {}; | |
spArr.forEach(x => { tCounter[x] = (tCounter[x] || 0) + 1; }); | |
// 將每個元素的重複出現次數清點過後比較,如果出現的次數相同表示有重複 | |
for (let e of spArr) { | |
// 如果重複次數小於等於 1 表示開頭字母只出現一次,其餘都不重複 falseCount + 1 | |
// 或者有任何元素的出現次數和陣列第一個元素不同 falseCount + 1 | |
(tCounter[spArr[0]] <= 1) || (tCounter[spArr[0]] !== tCounter[e]) ? falseCount++ : e; | |
}; | |
// 將不重複計數器 falseCount 轉為布林值輸出,大於 0 就會轉成 true | |
return !!falseCount; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment