码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode 3] Longest Substring Without Repeating Characters

时间:2015-05-10 23:36:51      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:

https://leetcode.com/problems/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.

比较low的方法是直接暴力,时间复杂度是o(n2),但是仔细观察一下,就会发现可以优化。

例如,"abcdebrt" ,i 指针首先在字符串的起始位置当我们发现第二个 b 时 j 指针到索引为6的位置,这个时候计算一下 maxLength 为5(j - i),那么第二次遍历的时候 i 指针可以直接跳到 c 的位置, j 指针继续往前走,从 i 往后算如果再遇到重复,就更新 maxLength。这样的话,只遍历了字符串一遍(j 指针),时间复杂度降为o(n),太high了,代码如下:

/**
 * 两种情况下需要更新maxLength
 * 1. 发现重复的character
 * 2. 到了最后一个character(且最后一个character与之前的没有重复)
 */


class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        vector<int> hashmap(256, -1);
        int i = 0;
        int maxLength = 0;
        for (int j = 0; j < s.size(); j++) {
            // s[j] 出现
            if (hashmap[s[j]] >= i) {
                maxLength = max(maxLength, j - i);
                i = hashmap[s[j]] + 1;
            } else if (j == s.size() - 1) { //如果有重复,就不用判断最后一个了
                maxLength = max(maxLength, j - i + 1);
            }
            
            hashmap[s[j]] = j;
        }
        return maxLength;
    }
};

[LeetCode 3] Longest Substring Without Repeating Characters

标签:

原文地址:http://www.cnblogs.com/jianxinzhou/p/4493192.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!