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




  • 相关阅读:
    struts2类型转换2
    list集合排序3
    list集合排序2
    list集合排序
    JSON
    Java获取文件Content-Type(Mime-Type)
    struts2文件下载
    获取文件大小
    struts2国际化
    人人都是产品经理
  • 原文地址:https://www.cnblogs.com/zxqstrong/p/4561902.html
Copyright © 2011-2022 走看看