Leetcode题解 - 3. Longest Substring Without Repeating Characters

来源:互联网 发布:单用户商城源码 编辑:程序博客网 时间:2024/05/23 01:12

题目

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. 使用一个临时字符串存放子串T
2. 每次从输入中获取一个字符C,并检查已有的子串T中是否已经存在该字符
    - 如果存在,删除该字符之前的所有字符和它自己
3. 将C追加在子串T的尾部
4. 获取子串T的长度,并决定是否要更新最大值MAX
5. 重复1~4步骤,直到输入的所有的字符都处理完
6. 返回最大值MAX


本人的解

根据上述思路,代码如下。耗时29毫秒。

class Solution {public:/* 29 ms, Your runtime beats 51.30% of cpp submissions */int lengthOfLongestSubstring(string s) {int max = 0;string t("");for( int i = 0; i < s.length(); i++ ) {size_t pos = t.find(s[i], 0);if( pos != string::npos ) t.erase(0, pos + 1);t.append(1, s[i]);if( t.length() > max ) max = t.length();}return max;}};

改进版。
由于题目要求返回长度,而不是子字符串。所以可以使用string::back()函数取最后一个字符,处理完后使用string::pop_back()删除最后一个字符。
改进后,耗时12毫秒,算是比较快的了。

class Solution {public:/* 12 ms, Your runtime beats 87.44% of cpp submissions */int lengthOfLongestSubstring(string s) {int max = 0;string t("");while( s.length() ) {char a = s.back();size_t pos = t.find(a, 0);if( pos != string::npos ) t.erase(0, pos + 1);t.append(1, a);if( t.length() > max ) max = t.length();s.pop_back();}return max;}};










0 0
原创粉丝点击