LeetCode Longest Substring Without Repeating Characters

来源:互联网 发布:sql字段别名 编辑:程序博客网 时间:2024/06/05 06:35


太久不动手折腾一下午,居然不如从前了。

收藏一个评论区特别精炼的代码。



int lengthOfLongestSubstring2(string s) {int m[129] = { 0 }; //每个字母的位置+1,非常巧妙int i, j;int cnt = 0, pre = 0; //cnt当前长度,pre当前计数开始的位置int max = 0;int c;//当前字母for (i = 0; c = s[i]; i++) {if (pre < m[c]) {//如果当前计数开始的位置就是字母c(因为m[c]比c上次的位置大1)if (max < cnt)max = cnt;cnt = i - m[c];//更新当前长度pre = m[c];//从上次C的位置的下一个字母开始计数}cnt++;m[c] = i + 1;}return max > cnt ? max : cnt;}




0 0
原创粉丝点击