剑指Offer(第二版)面试题48:最长不含重复字符的子字符串
2018-01-08 15:31
465 查看
剑指Offer(第二版)面试题48:最长不含重复字符的子字符串
题目要求:
输入一个字符串(只包含a~z的字符),求其最长不含重复字符的子字符串的长度。例如对于arabcacfr,最长不含重复字符的子字符串为acfr,长度为4。解题思路:
动态规划。用dp[]记录状态,dp[i]表示以下标为i的字符结尾不包含重复字符的最长子字符串长度。初始化dp[0] = 1,求maxdp。每次可以根据dp的前一个状态推导出后一个状态,因此可以省略dp数组,使用一个变量记录dp值,使用maxdp记录最大的dp值。C++代码
#include <iostream> #include <string> using namespace std; int longestSubstringWithoutDuplication(const string& str); int main() { string s = ""; while(s != "-1") { cout << "input a string:" << endl; cin >> s ; int result = longestSubstringWithoutDuplication(s); cout << s <<" longest substring count is "<< result <<endl; } return 0; } int longestSubstringWithoutDuplication(const string& str) { int currentCount = 0; int maxCount = 0; int* preLocation = new int[26]; for (int i = 0; i < 26; ++i) { preLocation[i] = -1; } cout << str.size() <<str.length(); for (int i = 0; i < str.size(); ++i) { int pre = preLocation[str[i] - 'a']; if(pre < 0 || i - pre > currentCount) { ++currentCount; } else { if(currentCount > maxCount) maxCount = currentCount; currentCount = i - pre; } preLocation[str[i] - 'a'] = i; } if(currentCount > maxCount) maxCount = currentCount; delete[] preLocation; return maxCount; }
参考文献
剑指offer第二版-48.最长不含重复字符的子字符串(动态规划)相关文章推荐
- 剑指offer面试题48: 最长不含重复字符的子字符串
- 剑指Offer-48:最长不含重复字符的子字符串
- 最长不含重复字符的子字符串
- 从字符串中找出一个最长的不含重复字符的子字符串
- 面试题:最长不含重复字符的子字符串
- 百度面试题 求字符串中不含重复字符的最长子串长度
- LeetCode 题解 3. Longest Substring Without Repeating Characters(最长不含重复字符的子字符串)
- 定义一个栈的数据结构,实现min函数,要求push,pop,min时间复杂度是0(1);找出字符串中的最长子串,要求子串不含重复字符,时间复杂度是O(n);
- 3. Longest Substring Without Repeating Characters 无重复字符的最长子字符串
- 求字符串中不含重复字符的最长子串的长度
- 剑指Offer(第二版)面试题3:数组中的重复元素
- 在英文字符串中找第一个最长不含重复字符的子串高效实现(修改版)
- 3. Longest Substring Without Repeating Characters(计算不含重复字符的最长子串的长度)
- 关于 最长的子字符串不重复字符 相关js算法问题
- 求字符串最长不含重复字符的子串长度
- 剑指offer——面试题55:字符流中第一个不重复的字符
- 不含重复字符的最长子串--O(n)
- Coding Puzzels - 51 没有重复字符的最长的子字符串
- 剑指offer-面试题55:字符流中第一个不重复的字符
- 《剑指Offer》学习笔记--面试题55:字符流中第一个不重复的字符