Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given "pwwkew"
, the answer is "wke"
, with the length of 3. Note that the answer must be a substring, "pwke"
is a subsequence and not a substring.
==================
题目:给定一个字符串,超出最长的没有重复元素的公共字串?
注意:结果的长度必须是字串的长度.
=========
思路:
假设字串中含有重复字符,则父串中一定含有重复字符,单个子问题就可以决定父问题,
因此可以考虑贪心法.
与动态规划的区别,在动态规划里,单个子问题只能影响父问题,不足以决定父问题.
=
从左向右扫描数组,当遇到重复字母时,以上一个重复字母的index+1,作为新的搜索起始位置,
直到最后一个字母,复杂度为O(n).
如图,
===========
code如下:
public: int lengthOfLongestSubstring(string s){ int length = s.size(); vector<int> record(255,-1); int start = 0;//record the start location of current string int max_len = 0; for(int i = 0;i<length;i++){ if(record[s[i]] >= start){ max_len = max(max_len,i-start); start = record[s[i]]+1; } record[s[i]] = i; }///for return max(max_len,length-start); } };
=====
这里使用了一种很常用的方法,利用有限数组来判断重复元素的存在(!!!!这是很重要的一种思想,很多leetcode上面的题都会借鉴这个思路).
在本题中就是 vector<int> record(255,-1);
为什么会定义255个,因为ascii码包括所有的ascii编码.
---------