問題:給定一個字符串,查找其最長無重複字符的子串,並輸出其長度spa
示例:code
輸入:"abcabcbb"blog
輸出:3索引
輸入:"bbbbbb"字符串
輸出:1string
C解決方案:class
#include <string.h> //判斷最後一個字符在前面的字符串中是否已經存在 int judgeRepeat(char * s,int left, int right){ while(left<right){ if(s[left]==s[right]){ return left; } left++; } return -1; } int lengthOfLongestSubstring(char * s){ //判斷字符串長度是否小於1,小於1直接返回字符串長度 int length = strlen(s); if(length<=1){ return length; } int left = 0; int right = 0; int maxLength = right-left+1; //循環,每次增長一個字符,判斷該字符在以前的字符串中是否已經存在, //存在,則將left變爲存在的字符串索引+1,不存在,則判斷輸出的長度是否應該改變 while(right<length){ int judge = judgeRepeat(s,left,right); if(judge==-1){ if(maxLength<right-left+1) maxLength = right-left+1; }else{ left = judge+1; } right+=1; } return maxLength; }