LeetCode3 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)、当前最长无重复字符子串的起始位置。(2)、当前最长无重复字符子串的长度。(3)、由前两项信息可以截取字串,对下一个字符进行判断,若在字串中未找到该字符,则(1)中信息不变,(2)中信息要加1;若在字符串中找到该字符,返回该字符在字串中的位置,以(1)信息+重复位置+1作为新的起始位置,以(2)-重复位置作为新的(2)。


class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        char cur;
        int i;
        int max=1;
        int index_begin,index_repeat;
        int count=1;
        string curmax_string;
        if(s.length()==0)
        {
            return 0; 
        }
        index_begin=0;
        for(i=1;i<s.length();i++)
        {
            cur=s[i];
            curmax_string=s.substr(index_begin,count);
            if((index_repeat=curmax_string.find_last_of(cur))==string::npos)
               {
                   count++;
                   if(count>max)
                       max=count;
               }
            else
               {
                   count = count - index_repeat;
                   index_begin = index_begin+index_repeat+1;
               }

               }
               return max;
    }
};

int find_first_of(char c, int start = 0):
查找字符串中第1个出现的c,由位置start开始。如果有匹配,则返回匹配位置;否则,返回-1.默认情况下,start为0,函数搜索整个字符串。
int find_last_of(char c):
查找字符串中最后一个出现的c。有匹配,则返回匹配位置;否则返回-1.该搜索在字符末尾查找匹配,所以没有提供起始位置。
npos 是这样定义的:
static const size_type npos = -1;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值