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;
        }
  • 相关阅读:
    内部类概述和访问特点
    权限修饰符 权限
    抽象类和接口作为返回值类型的问题
    抽象类和接口作为形参问题
    jdbc:java数据库连接
    类与类、类与接口、接口与接口的关系
    接口
    抽象类
    多态
    继承中构造方法的关系
  • 原文地址:https://www.cnblogs.com/dplearning/p/4270121.html
Copyright © 2011-2022 走看看