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




  • 相关阅读:
    Cocos2dx for Windows Phone 8 发布
    Tiny Core Linux 4.7 发布
    走进 Google 的 Go 语言
    XCache 3.0.0 发布,PHP 性能提升方案
    Entropy Broker 2.0 发布,加密安全随机数
    Windows Phone 8 同步工具已提供,功能对比表
    PolarSSL 1.2.0 发布,SSL 加密库
    YUI 2 存在SWF漏洞,YUI 3 不受影响
    Google改进Dart并提供SDK
    Expression Blend实例中文教程(3) 布局控件快速入门Grid
  • 原文地址:https://www.cnblogs.com/zxqstrong/p/4561902.html
Copyright © 2011-2022 走看看