算法打卡第十天 (动态规划)

88 阅读2分钟
  1. 剑指 Offer 46. 把数字翻译成字符串
  2. 剑指 Offer 48. 最长不含重复字符的子字符串

剑指 Offer 46. 把数字翻译成字符串

给定一个数字,我们按照如下规则把它翻译为字符串:0 翻译成 “a” ,1 翻译成 “b”,……,11 翻译成 “l”,……,25 翻译成 “z”。一个数字可能有多个翻译。请编程实现一个函数,用来计算一个数字有多少种不同的翻译方法。

题意理解 数字可翻译的范围0-25;

  1. 及新增数 fn(n)-fn(n-1) = fn(n-1) + fn(n-2)
  2. 存储满足条件才符合上面条件及10<=两位数<=25
  3. 一个变量用来存储count中方法,一个变量用来存储上一次符合条件的和

测试用例 输入: 12258 输出: 5 解释: 12258有5种不同的翻译,分别是"bccfi", "bwfi", "bczi", "mcfi"和"mzi"

动态规划

var translateNum = function(num) {
    const str = String(num);
    let count = 1,
        p = 0,
        q = 0;
    for (let i = 0; i < str.length; i++) {
        p = q;
        q = count;
        count = 0;
        count += q;
        if (i === 0) {
            continue;
        }
        const cStr = str[i - 1] + str[i];
        if (cStr <= "25" && cStr >= "10") {
            count += p
        }
    }
    return count
};

利用数字求余

function translateNum(num) {
    let count = 1,
        p = 1,
        pre = num % 10,
        next = num % 10;
    while (num) {
        num = Math.floor(num / 10);
        pre = num % 10;
        let currentNum = pre * 10 + next
        let currentCount = (currentNum >= 10 && currentNum <= 25) ? p + count : count
        // 这样写是用来存储上一次符合条件的值
        p = count;
        count = currentCount;
        next = pre;
        console.log(p, count);
    }
    return count
}

剑指 Offer 48. 最长不含重复字符的子字符串

请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。

题意理解 找出字符串中不重复连续的子字符串的最大长度

  1. 使用哈希表及Map,保存当前字符的位置
  2. 使用maxLength保存当前不重复最大长度
  3. currentLength保存当前位置不重复的长度
  4. 保存时值用索引+1表示,因为索引从0开始的,+1方便计算长度

测试用例 输入: "abcabcbb" 输出: 3 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。

动态规划 + 哈希表

var lengthOfLongestSubstring = function(s) {
    const map = new Map()
    let maxLength = 0;
    let currentLength = 0;
    for (let i = 0; i < s.length; i++) {
        const currentIndex = map.get(s[i]) || 0
        map.set(s[i], i + 1)
        currentLength = currentLength < i + 1 - currentIndex ? currentLength + 1 : i + 1 - currentIndex;
        maxLength = Math.max(maxLength, currentLength)
    }
    return maxLength
};