/** * @param {number} n * @return {string} */ functionmethod1(str) { let count = 1; let result_str = ""; for (let i = 0, len = str.length - 1; i < len; i++) { if (str[i] == str[i + 1]) { count++; //如果是倒数第二个跟倒数第一个相等,直接返回 if (i == len - 1) { result_str += count + "" + str[i] + ""; return result_str; } } else { result_str += count + "" + str[i] + ""; //重新计数 count = 1; //如果是倒数第二个跟倒数第一个不相等,处理一下最后一位 if (i == len - 1) { result_str += count + "" + str[i + 1] + ""; return result_str; } } } } /*传入待处理字符串str,返回描述字符串result_str*/ functioncountAndSay(n) { let arr = ["1", "11"]; if (n == 1) { return"1"; } if (n == 2) { return"11"; }
for (let i = 2; i < n; i++) { arr.push(method1(arr[i - 1])); } return arr[n - 1]; }
参考时间消耗最低的代码
1 2 3 4 5 6 7
var countAndSay = function (n) { let prev = "1"; for (let i = 1; i < n; i++) { prev = prev.replace(/(\d)\1*/g, (item) =>`${item.length}${item[0]}`); } return prev; };