【leetcode】Longest Substring Without Repeating Characters

题干

Given a string, find the length of the longest substring without repeating characters.

Example 1:

Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:

Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters

题解

看到题目第一眼,企图想暴力解题,但是中等难度等题怎么可能给你暴力过😔肯定要找规律。

首先想到的是KMP算法(雾),但是没有模式串,所以感觉这题不是KMP。

源码:

//  企图通过暴力扫描解决,直接在最后一个测试用例上T了
   int lengthOfLongestSubstring(string s) {
       int max = 0;
       for(int i = 0; i < s.length(); i++){
           int l = 0;
           for(int j = i + 1; j <= s.length(); j++){
               if(!check(s,i,j)) break;
               else l++;
           }
           if(l > max) max = l;
       }
       return max;
   };
   bool check(string s, int h, int t) {
       int a[128] = {0};
       for(int i = h; i < t; i++){
           if(a[s[i]]>=1)return false;
           a[s[i]]++;
       }
       return true;
   }

正解:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int max = 0;
        //设置一个h指代字串头,t指代字串尾,i作为一个零时变量用于迭代
        int i,t,h = 0;
        //字串尾不断后移
        for(t = 0; t < s.length(); t++){
            //串尾每增加一个字符就从头到位扫描一遍,看有没有重复都。
            for(i = h; i < t; i++){
                //下一句是让算法不被T的关键
                //即,若在扫描后发现有重复的字符,则舍弃新增字符与之前的所有字符。
                //下一段截取的字串在该字符的下一位。
                if(s[t] == s[i]){
                    h = i + 1;
                    break;
                }
            }
            if(t-h+1>max){
                max = t-h+1;
            }
        }
        return max;
    };

};

posted @ 2021-01-05 00:10  VanGy  阅读(52)  评论(0编辑  收藏  举报