LeetCode之Longest Substring Without Repeating Characters

来源:互联网 发布:mac 能用的刻录机 编辑:程序博客网 时间:2024/05/28 14:56

一、题目

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.

二、考虑过程

比如输入jbpnbwwd,首先从头开始统计子字符串,当出现重复字符时,开始下一个子字符串的统计,但是要注意下一个子字符串的统计位置应该是从第一次出现相同字符的下一位开始。

三、代码

class Solution {public:    int lengthOfLongestSubstring(string s) {    string ans[2] = {"",""};    int len[2] = {0,0};    for(unsigned int i=0; i<s.size(); i++){        string::size_type pos = ans[1].find(s[i]);        if(pos==string::npos){            ans[1] += s[i];            len[1]++;        }else{            if(len[0]<len[1]){                len[0] = len[1];                ans[0] = ans[1];            }            len[1] = 0;            ans[1] = "";            string::size_type rpos = s.rfind(s[i],i-1);            i = i - (i-rpos-1);   //这里注意为什么从重复字符的第一个的下一位开始:如果再将位置往前移的话肯定包括了当前的重复字符,只有从下一位才不会同时包含两个相同字符。            i--;        }    }    if(len[0]<len[1]){        return len[1];    }else{        return len[0];    }    }};

四、另一种

另一种方式:考虑到最大子串要么是整个字符串;要么就是两个相同字符间距离。可以用map存储第一个字符,当出现相同字符时加以判断。
这里写图片描述

class Solution {public:    int lengthOfLongestSubstring(string s) {        int maxl=0,tem=0;        unordered_map<char,int> con;        for(int i=0; i<s.size(); i++){            if(con.count(s[i])){                tem = max(tem,con[s[i]]+1);  //一般情况下,应该时map记录的两个字符间距,但是,如果出现两个相同字符串交叉问题,就要修改一下。            }            con[s[i]] = i;            maxl = max(maxl,i-tem+1);        }        return maxl;    }};
0 0
原创粉丝点击