剑指 Offer 46. 把数字翻译成字符串
题目描述:剑指 Offer 46. 把数字翻译成字符串
题解思路:面试题46. 把数字翻译成字符串(动态规划,清晰图解)
class Solution {
public:
int translateNum(int num) {
string str = to_string(num);
int strLength = str.size();
vector<int> dp(strLength + 1);
dp[0] = 1; //注意dp[0]为1
dp[1] = 1;
if(strLength <= 1)return dp[strLength];
for(int i = 2; i <= strLength; i++){
if(str[i - 2] == '1' || (str[i - 2] == '2' && str[i-1] <= '5')){
dp[i] = dp[i-2] + dp[i - 1];
}else{
dp[i] = dp[i-1];
}
}
return dp[strLength];
}
};
剑指 Offer 48. 最长不含重复字符的子字符串
题目描述:剑指 Offer 48. 最长不含重复字符的子字符串
题解思路:
面试题48. 最长不含重复字符的子字符串(动态规划 / 双指针 + 哈希表,清晰图解)
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int result = 0, temp = 0;
map<char, int> m;
for(int i = 0; i < s.length(); i++){
temp = m.count(s[i]) == 0 ? temp + 1: min(temp + 1,i - m[s[i]]);
m[s[i]] = i;
result = max(result, temp);
}
return result;
}
};