这一题的目标是找出字符串中最长的子串,要求字符串无重复。
先是一个错误的解法:
int lengthOfLongestSubstring(char* s) { int length = strlen(s); if(length==0) return 0; int curLength = 1; int maxLength = 1; int start = 0; int i,j,k; for(i=0;i<length;i++){ for(j=i+1;j<length;j++){ for(k=i;k<j;k++){ if(s[k]==s[j]) break; } if(k!=j) break; else curLength++; } if(curLength>maxLength) maxLength = curLength; curLength = 1; } return maxLength; }
i<length-maxLength
int isUnique(char* s,int start,int end); int lengthOfLongestSubstring(char* s) { int length = strlen(s); if(length==0) return 0; int start = 0; int end = 1; int maxLength = 1; int i; while(start<length&&end<length){ if(isUnique(s,start,end)) ++end; else ++start; maxLength = maxLength>(end-start)?maxLength:(end-start); } return maxLength; } int isUnique(char* s,int start,int end){ char temp = s[end]; int i; for(i=start;i<=end-1;i++){ if(s[i]==temp) return 0; } return 1; }
public class Solution { public int lengthOfLongestSubstring(String s) { int n = s.length(); Set<Character> set = new HashSet<>(); int ans = 0, i = 0, j = 0; while (i < n && j < n) { // try to extend the range [i, j] if (!set.contains(s.charAt(j))){ set.add(s.charAt(j++)); ans = Math.max(ans, j - i); } else { set.remove(s.charAt(i++)); } } return ans; } }
int lengthOfLongestSubstring(char* s) { int n = strlen(s); int start; int end; int maxLength = 0; int* set = (int*)malloc(sizeof(int)*128); memset(set,0,sizeof(int)*128); for(start=0,end=0;end<n;end++){ start = set[s[end]]>start?set[s[end]]:start; maxLength = maxLength>(end-start+1)?maxLength:(end-start+1); set[s[end]] = end+1; } return maxLength; }
set[s[end]] = end+1;