【Leetcode 3】Longest Substring Without Repeating Characters

来源:互联网 发布:天龙抢号软件 编辑:程序博客网 时间:2024/06/07 11:26

题意:给定一个字符串,求出最长的子串,这个子串中要求不能有相同的字符。

思路:hash的思想,开个一个数组记下前一个相同字符的位置,然后在遍历过程中记下最大值(相当于往前能延伸的最前面的位置),即可求解答案。

class Solution {public:    int lengthOfLongestSubstring(string s) {       int pos[300];       memset(pos,-1,sizeof(pos));       int ans=0;       int now_max=-1;//往前能延伸的最前面的位置       for(int i=0;i<s.length();++i){       if(pos[s[i]]>now_max)      now_max=pos[s[i]];       ans=max(i-now_max,ans);       pos[s[i]]=i;       }       return ans;    }};


提交结果:


0 0
原创粉丝点击