标签:leetcode
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.
算法:用map判断字符是不是出现过
java:
public class Solution { public int lengthOfLongestSubstring(String s) { int len = s.length(); if(len<=1){ return len; } int[] map=new int[256]; int maxLen=-1; int sum=0; int i=0; while(i<len){ //第一次出现 if(map[s.charAt(i)]==0){ sum++; //存储第一次出现的下标+1(如果存储i的话,下标为0的元素也可能重复,所以存储i+1) map[s.charAt(i)]=i+1; i++; }else{ if(sum>maxLen){ maxLen=sum; } int start=map[s.charAt(i)]; sum=i-start+1; Arrays.fill(map,0); i=start; sum=0; } } if(sum>maxLen){ maxLen=sum; } return maxLen; } }
class Solution { public: int lengthOfLongestSubstring(string s) { int a[256]; memset(a,0,256*4); int i=0; int sum=0; int max=0; while(i<s.length()){ if(a[(int)s[i]]==0){ a[(int)s[i]]=i+1; sum++; if(sum>max){ max=sum; } i++; }else{ i=a[(int)s[i]]; memset(a,0,256*4); sum=0; } } if(sum>max){ max=sum; } return max; } };
Longest Substring Without Repeating Characters
标签:leetcode
原文地址:http://blog.csdn.net/u010786672/article/details/41252901