Leetcode :3. Longest Substring Without Repeating Characters

来源:互联网 发布:the weeknd earned it 编辑:程序博客网 时间:2024/06/15 06:04

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

Examples:

Given “abcabcbb”, the answer is “abc”, which the length is 3.

Given “bbbbb”, the answer is “b”, with the length of 1.

Given “pwwkew”, 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.

解题思路

对所有26个字母建立一个数组,数组内保存上一次遇到这个字母时的index,遍历字符串里每一个字符:

  1. 假设上一次遇到该字符的index晚于最近一次遇到重复的idx,那么更新idx,这是一个新的遇到重复的距离当前位置最近的index
  2. 如果本次遇到该字符与上一次遇到该字符的距离大于保存的最大值max,更新max
  3. 将上一次遇到当前字符的index更新为当前的位置

时间复杂度、空间复杂度分析

时间复杂度 O(n), 空间复杂度 O(1),其实可以用unordered_map

代码

class Solution {public:    int lengthOfLongestSubstring(string s) {        int count [256] = {0};// 26 个英文字母        memset(count, -1, sizeof(count));        int max = 0;        int idx = -1; // 保存最近一次遇到重复        for(int i =0 ;i < s.size(); ++i) {            if(count[s.at(i)] > idx)                idx = count[s.at(i)];            if((i - idx) > max)                max = i - idx;            count[s.at(i)] = i;        }        return max;    }};
0 0