标签:
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.
从左到右扫描,当遇到重复字母时,以上一个重复字母的index+1,作为新的搜索起始位置,直到最后一个字母。
/********************************* * 日期:2015-01-20 * 作者:SJF0115 * 题目: 3.Longest Substring Without Repeating Characters * 网址:https://oj.leetcode.com/problems/longest-substring-without-repeating-characters/ * 结果:AC * 来源:LeetCode * 时间复杂度:O(n) * 空间复杂度:O(1) * 博客: **********************************/ #include <iostream> #include <cstring> using namespace std; class Solution { public: int lengthOfLongestSubstring(string s) { int len = s.length(); if(len <= 1){ return len; }//if bool visited[256]; // 初始化 memset(visited,false,sizeof(visited)); // 计算 int max = 0,cur = 0,start = 0; for(int i = 0;i < len;){ // 没有元素和该元素重复 if(!visited[s[i]]){ visited[s[i]] = true; ++cur; ++i; }//if else{ // 更新最大长度 if(cur >= max){ max = cur; }//if cur = 0; memset(visited,false,sizeof(visited)); int index = 0; // 寻找之前重复元素的下一个元素的下标 for(int j = start;j < i;++j){ if(s[i] == s[j]){ index = j+1; break; }//if }//for start = index; i = index; } }//for if(cur > max){ max = cur; }//if return max; } }; int main(){ Solution solution; string str("abbacdafg"); int result = solution.lengthOfLongestSubstring(str); // 输出 cout<<result<<endl; return 0; }
[LeetCode]3.Longest Substring Without Repeating Characters
标签:
原文地址:http://blog.csdn.net/sunnyyoona/article/details/42918265