一、最长无重复子串
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc"
, with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b"
, with the length of 1.
分析:本题使用滑动窗口,利用map数据结构,头指针不停前移,如果头指针指向的当前字符已经存在于map中,那么尾指针取当前位置于该字符位置的最大值(尾指针看情况前移),之后更新ans并将当前字符纳入map。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
map<char,int> hash;
int ans=0;
//map.find通过key找value
for(int i=0,j=0;j<s.size();j++)
{
if(hash.find(s[i])!=hash.end())//找到了
{
i = max(hash.find(s[j])->second,i);
}
ans = max(ans,j-i+1);
hash[s[j]] = j+1;
}
return ans;
}
};
二、最长回文串
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd" Output: "bb"
分析:
1.可使用dp,定义状态i,j为字符串i到j是否为回文串
P(i,j)=(P(i+1,j−1) and Si==Sj)
The base cases are:
P(i,i)=true P(i, i) = true P(i,i)=true
class Solution {
public:
string longestPalindrome(string s) {
int l = s.size();
if(l==0)
return "";
bool dp[l][l] ;
for(int i=0;i<l;i++)
for(int j=0;j<l;j++)
dp[i][j]=false;
int mi=0, mj=1;
for(int i=0;i<l;i++)
{
dp[i][i] = true;
if(i != l-1 )
if(s[i]==s[i+1])
{
dp[i][i+1]=true;
mi=i;
mj=2;
}
}
for(int d=2;d<l;d++)
for(int i=0;i<l-d;i++)
{
int j=i+d;
if(dp[i+1][j-1] && s[i]==s[j])
{
dp[i][j]=true;
mi=i;
mj=d+1;
}
}
cout<<mi<<mj;
return s.substr(mi,mj);//mi为起始位置,j为长度
}
};
2.可以使用从中心扩展法
分析:回文串最多有2n-1个中心,我们遍历这些中心,寻找最长串
class Solution {
public:
string longestPalindrome(string s) {
int l = s.size();
if(l==0)
return "";
int start = 0;
int len;
for(int i=0;i<l-1;i++)
{
int len1 = expend(s,i,i);
int len2 = expend(s,i,i+1);
if(max(len1,len2)>len)
{
len = max(len1,len2);
start = i - (len-1)/2 ;
}
cout<<start<<' '<<len<<endl;
}
return s.substr(start,len);
}
int expend(string s, int L,int R)
{
while(L>=0 && R<s.size() && s[L]==s[R])
{
L--;
R++;
}
return R-L-1;
}
};