Longest Substring Without Repeating Characters

3. Longest Substring Without Repeating Characters

My Submissions
Total Accepted: 115367 Total Submissions: 548630 Difficulty: Medium

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

Subscribe to see which companies asked this question

Show Tags
Show Similar Problems
Have you met this question in a real interview? 
Yes
 
No
 

Discuss

 

首先还是自己的思路:主要是遍历数组, 结果显示比一半的人用的时间多,那一半人是怎么做的呢

class Solution {

public:
    /*
     * 这种题还是数组,循环遍历字符串,设置两个下标left, right,设置一个max,初始化位1
     * 然后右下标开始移动,如果在left和right之间出现过,就重新设置left为为字符串中和右下标相同的字符的下一位
     * 如果没有出现就计算长度并与最大长度进行比较
     * */
    int lengthOfLongestSubstring(string s) {
        int len = s.length();
        if (len == 0) {
            return 0;
        } else if (len == 1) {
            return 1;
        }

        int left = 0;
        int right = 1;
        int max_len = 1;
        int tmp_max = 0;
        int index = left;
        for (; right<len; right++) {
            //查找前面的字符串里面是否出现s[right],
            for (index=left; index<right; index++) {
                if (s[index] == s[right]) {
                    //tmp_max = right - left;
                    //max_len = max(max_len, tmp_max);
                    left = index + 1;
                    break;
                }
            }
            //如果没有出现,就将最大长度 + 1
            if (index == right) {
                tmp_max = right - left + 1;
                max_len = max(max_len, tmp_max);
            }
        }
        return max_len;
    }
};

 

原文地址:https://www.cnblogs.com/SpeakSoftlyLove/p/5091152.html