欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > > 文章正文

[LeetCode] Longest Substring Without Repeating Characters,leetcoderepeating

来源: javaer 分享于  点击 41340 次 点评:167

[LeetCode] Longest Substring Without Repeating Characters,leetcoderepeating


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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
    	int pos[100];
		int aa=sizeof(pos);
		memset(pos,-1,sizeof(pos));//初始化,-1表示从未出现过
        int len=s.length();
		int max=0;
		int begin=0;//字符串计数的起始位置
		for(int i=0;i<len;i++)
		{
			int tem=s[i]-'a';//将字符转换为数字

			if(pos[tem]==-1)//如果s[i]从来没有出现过,进入
			{
				pos[tem]=i;	//标记s[i]出现的位置		
				if((i+1-begin)>max) max=i-begin+1;//当前位置i+1减去起始位置begin就是字符串的长度
			}
			else//如果该字符s[i]出现过
			{
				if(begin<=pos[tem]+1)//如果出现的位置在begin之后,则对begin的位置进行更改。
				begin=pos[tem]+1;//意思就是说begin之前的字符已经处理过了,在begin之前出现过就不考虑了
				pos[tem]=i;//更新s[i]出现的位置
				if((i+1-begin)>max) max=i-begin+1;//计算长度是否为最大,如果是更新max
				
			}
		}
        return max;
    }
};



相关文章

    暂无相关文章

用户点评