首页 > 其他 > 详细

LeetCode 3: Longest Substring Without Repeating Characters

时间:2018-08-13 19:31:14      阅读:189      评论:0      收藏:0      [点我收藏+]

Description:

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

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.


描述:

给定一个字符串,返回该字符串最长无重复子串,即最长的不包含重复字符的子字符串。

示例:

给定字符串 “abcabcbb”, 答案为 “abc”,长度为3;
给定字符串 “bbbb”, 答案为 “b”, 长度为1;
给定字符串 “pwwkew”, 答案为 “wke”,长度为3. 注意,答案必须为子串,“pwke”是子序列,但不是子字符串。

 

方法一:暴力破解

遍历字符串的每个子串,并判断相应子串中是否存在重复字符。

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if(s.length() == 0) {
            return 0;
        }
        int maxLen = 0;
        for(int i = 0; i < s.length(); i++) {
            for(int j = i + 1; j < s.length() + 1; j++) {
                if(hasRepeatChar(s, i, j)) {
                    break;
                }
                int len = j - i;
                if(len > maxLen) {
                    maxLen = len;
                }
            }
        }
        return maxLen;
    }
    
    bool hasRepeatChar(string s, int start, int end) {
        set<int> c;
        for(int i = start; i < end; i++) {
            if(c.count(s[i]) != 0) {
                return true;
            }
            c.insert(s[i]);
        }
        return false;
    }
};

该方法的时间复杂度为O(n3),空间复杂度为O(n)。

然而,该方法时间复杂度较高,导致Time Limit Exceeded.

 

方法二:滑动窗口

 

LeetCode 3: Longest Substring Without Repeating Characters

原文:https://www.cnblogs.com/alpaca/p/9470059.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!