LeetCode OJ-3.Longest Substring Without Repeating Characters(最长无重复子串)

LeetCode OJ-3.Longest Substring Without Repeating Characters(最长无重复子串)

题目描述

3. Longest Substring Without Repeating Characters

Add to List

QuestionEditorial Solution

My Submissions

  • Total Accepted: 227666
  • Total Submissions: 964454
  • Difficulty: Medium
  • Contributors: Admin

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.

题目理解

​ 题目简单来说就是求最长无重复子串,子串是连续的。做起来就比较简单,但要注意细节:1.要记录最长的无重复子串起始与结尾位置,以便求解最长长度;2.出现在未出现重复的情况下,要及时更新最大长度;3.检测重复。简单的实现方法时间复杂度O(n^2),空间复杂度O(1),具体代码如下:

Code

#define MAX(m, n) ( (m > n) ? m : n ) 

int get_longest_substring_len(const char *str, size_t sz)
{
    int max_len = 0;
    int i = 0;  //起始位置
    int j = 0;  //结束位置
    int k = 0;
    while (j < sz) {
        k = i;
        while (k < j) {  //检测j之前是否存在重复元素
            if (str[k] == str[j]) {  //存在重复元素则跳出循环
                break;
            }
            else {
                ++k;
            }
        }

        if (k == j) {  //j之前未检测到重复元素
            max_len = MAX(max_len, j - i + 1);
            ++j;
        }
        else {  //j之前存在重复元素
            ++i;
            j = i;
        }
    }

    return max_len;
}

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        size_t sz = s.length(); 
        return get_longest_substring_len(s.c_str(), sz); 
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值