透過 JavaScript 中的改變大小寫來建立排列
問題
我們需要編寫一個 JavaScript 函式,它接受一個字串字元 str 作為第一個也是唯一引數。
我們的函式可以單獨地將每個字母轉換為小寫或大寫以建立另一個字串。我們應該返回我們建立的所有可能字串的列表。
例如,如果函式的輸入是
輸入
const str = 'k1l2';
輸出
const output = ["k1l2","k1L2","K1l2","K1L2"];
示例
程式碼如下 −
const str = 'k1l2'; const changeCase = function (S = '') { const res = [] const helper = (ind = 0, current = '') => { if (ind >= S.length) { res.push(current) return } if (/[a-zA-Z]/.test(S[ind])) { helper(ind + 1, current + S[ind].toLowerCase()) helper(ind + 1, current + S[ind].toUpperCase()) } else { helper(ind + 1, current + S[ind]) } } helper() return res }; console.log(changeCase(str));
輸出
[ 'k1l2', 'k1L2', 'K1l2', 'K1L2' ]
廣告