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

[leetcode]Longest Substring Without Repeating Characters

时间:2015-02-14 12:14:20      阅读:117      评论: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.

解题:

  首先想到是维护一个窗口,实现如下:

int lengthOfLongestSubstring(string s) {
        int start = 0;
		int lenOfLongest = 0;
		int curLenOfLongest = 0;
		int i;
		int j;
		int prev = 0;
		map<char, int> window; //字符->在s中的索引
		map<char, int>::iterator it;
		window.clear();
		for(i = 0; i < s.size(); i++){
			it = window.find(s[i]);
			if(it == window.end()){
			//如果当前字符不在window中,则加入,
				window[s[i]] = i;
				curLenOfLongest = i - start + 1;
			}else{
			//如果当前字符在window中,
			//则需要计算当前lenOfLongest,start后移到前一个s[i]的后一位,
			//删除window中前一个s[i]和s[i]之前的字符
			//...,start,...,prev,prev+1,...,i,...
				prev = it->second;
				curLenOfLongest = i - start;
				for(j = start; j <= prev; j++){
					window.erase(window.find(s[j]));
				}
				window[s[i]] = i;
				start = prev + 1;
			}
			if(lenOfLongest < curLenOfLongest)lenOfLongest = curLenOfLongest;
		}
		return lenOfLongest;
    }

  这个算法通过了,但时间上惨不忍睹,124ms。

  

[leetcode]Longest Substring Without Repeating Characters

标签:

原文地址:http://www.cnblogs.com/zhutianpeng/p/4291411.html

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