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




  • 相关阅读:
    京东基于大数据技术的个性化电商搜索引擎
    O2O的实时搜索引擎
    天猫11.11:搜索引擎实时秒级更新
    推荐系统和搜索引擎的关系
    1号店的分布式搜索引擎的架构实践
    详谈京东的商品搜索系统架构设计
    Office PPT保持提示无法保存Gill Sans 等非TrueType字体
    材价看板(2)- 运行两周的kanban,改进的起点
    材价看板(1)- 如何建立你的第一个kanban,看看这些暴露的问题你们有没有?
    Solr:Schema设计
  • 原文地址:https://www.cnblogs.com/zxqstrong/p/4561902.html
Copyright © 2011-2022 走看看