3. 无重复字符的最长子串
给定一个字符串,找出不含有重复字符的 最长子串 的长度。
示例:
给定 “abcabcbb” ,没有重复字符的最长子串是 “abc” ,那么长度就是3。
给定 “bbbbb” ,最长的子串就是 “b” ,长度是1。
给定 “pwwkew” ,最长子串是 “wke” ,长度是3。请注意答案必须是一个子串,”pwke” 是 子序列 而不是子串。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
map<char, int> ch;
int count = 0;
int i = 0;
int max = 0;
int start = 0;
while(i< s.size())
{
//ch中没有重复字母
if( ch.find(s[i]) == ch.end())
{
ch[s[i]] = i;
++count;
++i;
}
//重复字母没在当前计算子串中
else if(ch[s[i]] < start)
{
ch[s[i]] = i;
++count;
++i;
}
//字母重复,更新最值和子串起始位置
else
{
if(count > max)
max = count;
//更新
count = count-(ch[s[i]] - start);
start = ch[s[i]] + 1;
ch[s[i]] = i;
++i;
}
}
if(count > max)
max = count;
return max;
}
};
6. Z字形变换
将字符串 “PAYPALISHIRING” 以Z字形排列成给定的行数:
P A H N
A P L S I I G
Y I R
之后从左往右,逐行读取字符:”PAHNAPLSIIGYIR”
实现一个将字符串进行指定行数变换的函数:
string convert(string s, int numRows);
示例 1:
输入: s = “PAYPALISHIRING”, numRows = 3
输出: “PAHNAPLSIIGYIR”
示例 2:
输入: s = “PAYPALISHIRING”, numRows = 4
输出: “PINALSIGYAHRPI”
解释:
P I N
A L S I G
Y A H R
P I
/*依次将字符存入每行中,按照z型
*/
class Solution {
public:
string convert(string s, int numRows) {
std::string *rs = new std::string[numRows];
int row = 0;
int flog = 1;
int len = s.length();
if (numRows == 1)
return std::string(s);
for (int i = 0; i < len; i++)
{
rs[row] += s[i]; //0行,1行...n行,n-1行...0行
if (!row)
flog = 1;
else if (row == (numRows - 1))
flog = -1;
row += flog;
}
std::string result;
for (int i = 0; i < numRows; i++)
{
result += rs[i];
}
return result;
}
};