leetcode-Longest Substring Without Repeating Characters-3

原创 2016年08月29日 00:10:16

找出字符串的最长不重复子串的长度
直观的做法是枚举以每个元素为开头的最长不重复子串,更新长度,时间复杂度是ON^2,空间O1
更高效的做法:用一个hash表保存每个字符最后出现的下标,用一个指针i,表名当前最长不重复子串的首位置,遍历字符串,在hash表中找到当前字符最后一次出现的位置记为k,如果k>=i,说明当前字符在当前最长不重复子串中出现过了,那么更新i和hash[s[j]]。只需遍历一遍,时间复杂度是ON,空间O256(ascii字符其实只需128就够了)

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int i=0;
        int vis[300];
        for(int j=0;j<300;j++) vis[j]=-1;
        int ans=0;
        if(s.size()==0) return 0;
        if(s.size()==1) return 1;
        int len=s.size();
        for(int j=0;j<s.size();j++){
            if(vis[s[j]]>=i){
                ans=max(ans,j-i);
                cout<<i<<" "<<j<<" "<<j-i<<endl;
                i=vis[s[j]]+1;
            }
            vis[s[j]]=j;
        }
        ans=max(ans,len-i);
        return ans;
    }
};
版权声明:本文为博主原创文章,未经博主允许不得转载。

[LeetCode - 滑动窗口] 3. Longest Substring Without Repeating Characters

1 问题 Given a string, find the length of the longest substring without repeating characters. Exa...

LeetCode- 3. Longest Substring Without Repeating Characters

Description Given a string, find the length of the longest substring without repeating characters.E...

leetcode_3 - Longest Substring Without Repeating Characters

leetcode_3 : Longest Substring Without Repeating Characters标签(空格分隔): leetcode string twoPoints setGi...

LeetCode(3)--Longest Substring Without Repeating Characters

题目如下: Given a string, find the length of the longest substring without repeating characters. For ex...

LeetCode 3. Longest Substring Without Repeating Characters(线性处理, 哈希)

LeetCode 3. Longest Substring Without Repeating Characters(线性处理, 哈希) 1. 从左到右扫描字符串,读入每一位字符。当该位字符上一次出现...

【leetcode】【3】Longest Substring Without Repeating Characters

一、问题描述 Given a string, find the length of the longest substring without repeating characters. For e...

LeetCode#3. Longest Substring Without Repeating Characters

求最长子串(子串中没有重复元素)

LeetCode3. Longest Substring Without Repeating Characters(最长不重复子串)

题目链接:https://leetcode.com/problems/longest-substring-without-repeating-characters/ Given a ...

leetcode 3 -- Longest Substring Without Repeating Characters

leetcode 3 – Longest Substring Without Repeating Characters 题目: Given a string, find the lengt...

LeetCode题解(Week 16):3. Longest Substring Without Repeating Characters

原题目:Given a string, find the length of the longest substring without repeating characters. Example...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:leetcode-Longest Substring Without Repeating Characters-3
举报原因:
原因补充:

(最多只允许输入30个字)