zoukankan      html  css  js  c++  java
  • 【leetcode】Longest Substring Without Repeating Characters (middle)

    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.

    思路:

    关键是记录当前子串的起始位置和用hash表记录每个字母出现的情况。

    大神简约版的代码:

    class Solution {
    public:
        int v[256]; //asciib码最多256个
        int lengthOfLongestSubstring(string s) {
            memset(v,-1,sizeof(v)); //位置先全部赋值为-1
            int start = 0, ans = 0;
            for (int i = 0; i < s.size(); ++i) {
                if (v[s[i]] >= start) { //如果当前子串中已经出现了该字符 更新答案和起始位置
                    ans = ans > i - start ? ans : i - start;
                    start = v[s[i]] + 1;
                }
                v[s[i]] = i;
            }
            ans = ans > s.size() - start ? ans : s.size() - start;
            return ans;
        }
    };

    思路是一样的,我自己好长好慢的代码:

    int lengthOfLongestSubstring(string s) {
            unordered_map<char, int> v;
            int ans = 0;
            int len = 0;
            int start = 0; //记录当前子串的起始位置
            for(int i = 0; i < s.size(); i++)
            {
                if(v.find(s[i]) == v.end())
                {
                    len++;
                    v[s[i]] = i;
                }
                else
                {
                    string tmp = s.substr(i - len, len);
                    ans = (len > ans) ? len : ans;
                    len = i - v[s[i]];
                    for(int j = start; j < v[s[i]]; j++) //把重复字符前面的字符次数都置0
                    {
                        v.erase(s[j]);
                    }
                    start = v[s[i]] + 1;
                    v[s[i]] = i;
                    
                }
            }
            ans = (len > ans) ? len : ans;
            return ans;
        }
  • 相关阅读:
    除法
    01.python对象
    00.基础入门
    00.斐波那契数列第n项
    16.分治排序
    15.快速排序
    14.插入排序--希尔排序(缩小增量排序)
    13.插入排序--直接插入排序(简单插入排序)
    12.选择排序
    11.冒泡排序
  • 原文地址:https://www.cnblogs.com/dplearning/p/4270121.html
Copyright © 2011-2022 走看看