Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
For example, the longest substring without repeating letters for “abcabcbb” is “abc”, which the length is 3.
For “bbbbb” the longest substring is “b”, with the length of 1.
本题不仅要适应字母,非字母也要识别。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
const int ALL_LETTER = 256; //ASCII表的256个字符
int position[ALL_LETTER]; //记录每个字符出现的位置
int start = 0; //记录子字符串开始的位置
int max_len = 0; //记录最大子字符串的长度
fill(position, position+ALL_LETTER, -1);
for(int i = 0; i<s.size(); i++){
if(position[s[i]] >= start){
max_len = max(i-start, max_len);
start = position[s[i]] + 1;
}
position[s[i]] = i;
}
return max((int)s.size() - start, max_len);
}
};
fill函数的作用是:将一个区间的元素都赋予val值。
函数参数:fill(first,last,val); //first为容器的首迭代器,last为容器的末迭代器,val为将要替换的值。需要#include <algorithm>
。
fill_n函数的作用是:给你一个起始点,然后再给你一个数值count和val。把从起始点开始依次赋予count个元素val的值。
max()函数同样需要头文件#include <algorithm>