zoukankan      html  css  js  c++  java
  • leetcode3. Longest Substring Without Repeating Characters

    leetcode3. Longest Substring Without Repeating Characters

    题意:

    给定一个字符串,找到最长子串的长度,且该字串不含不重复字符。

    思路:

    用map存储,key为字符,value为index;
    O(n),遍历字符串,动态规划,一开始确定start的index,然后遍历,每次遍历的字符记作char,只要char对应map中value小于start,长度就在一直伸长,一旦大于或等于start,说明前一个该字符在start之后出现过一次,所以吧start点移动至前一个map[char]的index的下一位,更新map,然后继续遍历。

    ac代码:

    C++

    class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
            int res=0;
            int map[256];
            memset(map,-1,sizeof(map));
            int start = 0,temp = 0;
            
            for(int i=0;i<s.length();i++)
            {
                if(start <= map[s[i]])
                {                
                    start = map[s[i]] + 1;
                    temp = i - start + 1;                
                }
                else
                {
                    if(++temp > res) res = temp;
                }
                map[s[i]] = i;
            }
            return res;
        }
    };
    

    python

    class Solution(object):
        def lengthOfLongestSubstring(self, s):
            """
            :type s: str
            :rtype: int
            """
            char_map = {}
            start = temp = res = 0
            for i in range(len(s)):
                if s[i] in char_map and start <= char_map[s[i]]:
                    start = char_map[s[i]] + 1
                    temp = i - start +1
                else:
                    temp += 1
                    res = max(res, temp)
                char_map[s[i]] = i
            return res
    
  • 相关阅读:
    2019-10-28-开源项目
    2018-8-10-win10-uwp-MetroLog-入门
    2018-5-20-C#-BBcode-转-Markdown
    2018-8-10-win10-UWP-序列化
    2018-2-13-win10-uwp-BadgeLogo-颜色
    2019-1-25-WPF-ListBox-的选择
    2019-1-5-Windows-的-Pen-协议
    android studio打印
    Java 基本数据类型
    FreeRTOS 任务通知模拟计数型信号量
  • 原文地址:https://www.cnblogs.com/weedboy/p/7143410.html
Copyright © 2011-2022 走看看