pwstrick / daily

一份搜集的前端面试题目清单、面试相关以及各类学习的资料(不局限于前端)
2.39k stars 242 forks source link

回文子串 #1073

Open pwstrick opened 4 years ago

pwstrick commented 4 years ago

647. 回文子串

/**
 * @param {string} s
 * @return {number}
 */
var countSubstrings = function(s) {
    let len = s.length,
        count = 0;
    for(let i=0; i<len; i++) {
        for(let j=len-i; j>0; j--) {
            let sub = s.substr(i, j);       //i起始位置,j提取数量
            if(isValid(sub)) {
                count++;
            }
        }
    }
    return count;
};
function isValid(str) {
    let len = str.length;
    if(len == 1 || len == 0) {
        return true;
    }
    let start = str[0],
        end = str[len - 1];
    if(start != end) {
        return false;
    }
    return isValid(str.substr(1, len-2)); 
}