CPP
class Solution {
public:
int lengthOfLongestSubstring(string str) {
int max_len = -1;
if(str == ""){
max_len = 0;
}
int t[ 1<< 8] {0};
unsigned char c = 0;
for (int i = 0, s = 0; (c = str[i] ) != 0 ;t[c] = ++i) {
unsigned char c = (unsigned char) str[i];
if ( t[c] > s) {
s = t[c];
}else if ( max_len < 0 || i - s + 1 > max_len){
max_len = i - s + 1;
}
}
return max_len;
}
};
CPP vector实现
int lengthOfLongestSubstring(std::string str){
std::vector<int> m(1 << 8, -1);
int left = -1;
int res = 0;
int lengt = str.size();
for(int i = 0; i != lengt; i++) {
left = std::max(left, m[str[i]]);
m[str[i]] = i;
res = std::max(res, i - left);
}
return res;
}
GOLANG版本
func lengthOfLongestSubstring(str string) int {
m := make([]int,1 << 8)
for key,_ := range m {
m[key] = -1
}
var left int= -1
var res int = 0
for i,j := range str{
left = max(left, m[j])
m[j] = i
res = max(res, i - left)
}
return res
}