784.字母大小写全排列

给定一个字符串,通过将字符串中的每个字母转变大小写,可以获得一个新的字符。返回所有可能得到的字符串集合。(回溯法)

/**
 * @param {string} S
 * @return {string[]}
 */
var letterCasePermutation = function(S) {
    if(S==''){
        return [''];
    }
    const result = [];
    S = S.toLowerCase();
    result.push(S);
    for(let i=0; i<S.length; i++){
        if(S[i].match(/^[a-z]$/)){
            result.forEach((str)=>{
                const newStr = str.substring(0,i)+str[i].toUpperCase()+str.substring(i+1);
                result.push(newStr);
            });
        }
    }
    return result;
};

猜你喜欢

转载自www.cnblogs.com/ZLDJ-15-516/p/11038806.html