• leetcode--3


    1. 题目:

    Longest Substring Without Repeating Characters

    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.

    2. c++

    2.1

    class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            /*void *memset(void *s, int ch, unsigned n); 将s所指向的某一块内存中的每个字节的内容全部设置为ch指定的ASCII值, 块的大小由第三个参数指定,这个函数通常为新申请的内存做初始化工作, 其返回值为指向S的指针。
    需要的头文件<memory.h> or <string.h> */
         int locs[256];            //保存字符上一次出现的位置
            memset(locs, -1, sizeof(locs));
            int idx = -1, max = 0; //idx为当前子串的开始位置-1
            for (int i = 0; i < s.size(); i++)
            {
                if (locs[s[i]] > idx)//如果当前字符出现过,那么当前子串的起始位置idx为这个字符上一次出现的位置+1
                {
                    idx = locs[s[i]];
                }

                if (i - idx > max) //长度 max
                {
                    max = i - idx;
                }

                locs[s[i]] = i;
            }
            return max;
        }
    };

    3. python

       class Solution:

      def lengthOfLongestSubstring(self,s):

        res=0

        left=0

        d={}

        for i,ch in enumerate(s):    //enumerate 函数用于遍历序列中的元素以及它们的下标

          if ch in d and d[ch] >= left:

            left=d[ch]+1

          d[ch]=i

          res=max(res,i-left+1)

        return res




  • 相关阅读:
    C#实现office文档转换为PDF或xps的一些方法
    Asp.Net性能优化.
    我们该如何在网上寻找资源!!!!
    用谷歌浏览器来当手机模拟器
    js 文档高度
    文件的ContentType类型网页设计,HTML/CSS
    javascript 获取滚动条高度+常用js页面宽度与高度[转]
    学习MVC
    windows自带性能监控器
    C#语言规范之小结
  • 原文地址:https://www.cnblogs.com/zxqstrong/p/4561902.html
Copyright © 2020-2023  润新知