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

来源:互联网 发布:众银家苹果下载软件 编辑:程序博客网 时间:2024/06/10 20:01

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);     }};
0 0
原创粉丝点击