码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode-3

时间:2015-10-19 14:08:30      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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) {
    	int repeat, prej = 0;
    	unsigned int length = 0;
    	for (string::size_type i = 0; i < s.size(); i++){
    		for (string::size_type j = prej + 1; j < s.size(); j++){
    			repeat = 0;
    			for (string::size_type k = i; k < j; k++){
    				if (s[k] == s[j]){
    					repeat = 1;
    					prej = j;
    					if ((j - i) > length) length = j - i;
    					i = k;
    					break;
    				}
    			}
    			if (repeat == 0) {
    			    if(j == s.size() - 1)
    			        if ((j - i + 1) > length) length = j - i + 1 ;
    			    continue;
    			}
    			else break;
    		}
    	}
    	if(prej == 0) length = s.size();
    	return length;
    }
};

(1)说明  

i指向所判断子字符串的首元素,j指向所判断子字符串的尾元素,k用于遍历子字符串判断是否出现重复。prej用于记录上一次出现重复的字符的位子,若出现字符重复时,下次循环分别使ij指向两个重复字符的下一个位子。

(2)什么时候计算长度。

1)prej == 0,说明没有进入判断两个字符相同的逻辑;或者字符串的长度为0,没有进入第一重for循环;或者字符串的长度为1,没有进入第二重for循环。此时length = s.size();

2)当判断两个字符相同时。此时长度计算公式是 length = j - i ;

3)当j指向原字符串的尾元素时。此时长度计算公式是 length = j - i + 1 ;

LeetCode-3

标签:

原文地址:http://my.oschina.net/u/2463708/blog/518840

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!