[LeetCode-Algorithms-3] "Longest Substring Without Repeating Characters" (2017.9.8)

来源:互联网 发布:ipad不良信息过滤软件 编辑:程序博客网 时间:2024/06/05 18:51

题目链接:Longest Substring Without Repeating Characters


  • 题目描述:

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>题目思路:贪心,用两变量标记头尾,lon为所求的不重复字符串长度,从字符串头部开始,字符不重复时尾部变量往后增加,有字符和之前的字符串中某字母重复时,头部变量相应后推,由于使用内外双层循环,时间复杂度为O(n2)

<2>代码:

int lengthOfLongestSubstring(char* s) {    int len = strlen(s);    int lon = 0, i;    int bgt = 0, end;    for(end = 0; end < len; end++){        for(i = bgt; i < end; i++) {            if(s[end] == s[i])                 bgt = i + 1;        }        if(lon <= end - bgt)            lon = end - bgt + 1;    }    return lon;}

<3>提交结果:

这里写图片描述

<4>向他人学习:我在讨论中看到了C++的一种解法,52.2%的defeat率,觉得想法也是比较好,留在这里作为学习。

class Solution {public:    int lengthOfLongestSubstring(string s) {        int last[128];        int start = -1, ans = 0;        for(int i = 0; i < 128; i++) last[i] = -1;        for(int i = 0; i < s.length(); i++) {            if (last[s[i]] > start) start = last[s[i]];            last[s[i]] = i;            ans = ans > i-start ? ans : i-start;        }        return ans;    }};
阅读全文
0 0
原创粉丝点击