3. 无重复字符的最长子串 - 力扣(LeetCode)
思路:
这题我们用下标的方法来写
先定义一个左下标和一个右下标,写一个循环遍历整个数组(后面会解释falg的用途)
int max = 0; int left = 0, right = 0; int len = strlen(s); int falg = 0; int i = 0, j = 0; //遍历整个数组 for(i = 0; i < len; i++) { }
写一个if语句,当left小于right的时候,就写一个循环遍历从left下标开始的元素到right下标前面的元素,判断是否与right下标的元素相同,相同的话就跳出循环,令left 等于 与 right下标元素相同的元素后面的元素.怎么判断在left和right之间是否存在又和right相同的元素呢?这就用到了falg.如果left < right 的时候就让
right++; max = max = right - left + 1;
right++; max = max = right - left + 1; for(i = 0; i < len; i++) { if(left < right) { falg = 0; for(j = left; j < right; j++) { if(s[j] == s[right]) { falg = 1; break; } } if(falg == 1) { left = j + 1; } } max = max > (right - left + 1) ? max : (right - left + 1); right++; } 整体代码:(以力扣为例) int lengthOfLongestSubstring(char * s){ int max = 0; int left = 0, right = 0; int len = strlen(s); int falg = 0; int i = 0, j = 0; //遍历整个数组 for(i = 0; i < len; i++) { if(left < right) { falg = 0; for(j = left; j < right; j++) { if(s[j] == s[right]) { falg = 1; break; } } if(falg == 1) { left = j + 1; } } max = max > (right - left + 1) ? max : (right - left + 1); right++; } return max; }
整体代码:(以力扣为例)
int lengthOfLongestSubstring(char * s){ int max = 0; int left = 0, right = 0; int len = strlen(s); int falg = 0; int i = 0, j = 0; //遍历整个数组 for(i = 0; i < len; i++) { if(left < right) { falg = 0; for(j = left; j < right; j++) { if(s[j] == s[right]) { falg = 1; break; } } if(falg == 1) { left = j + 1; } } max = max > (right - left + 1) ? max : (right - left + 1); right++; } return max; }