zoukankan      html  css  js  c++  java
  • 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;
        }
    };

     

  • 相关阅读:
    mysql 约束条件 外键 forigen key 介绍
    【洛谷P4655】Building Bridges
    【CF1139D】Steps to One
    【YbtOJ#20073】钻石守卫
    【YbtOJ#20072】相似子串
    【YbtOJ#20071】礼物购买
    【洛谷P4149】Race
    【洛谷P2059】卡牌游戏
    【CF140C】New Year Snowmen
    【GMOJ4282】平方数游戏
  • 原文地址:https://www.cnblogs.com/SpeakSoftlyLove/p/5091152.html
Copyright © 2011-2022 走看看