【Leetcode】 3. 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.

分析:
这道题的意思是任意给一个字符串,找出其中最长的没有重复字符的子串。
解法一:
用一个变量start来记录子串的开始位置,用两个整型数组temp和pos来记录每个字符在子串中是否出现和出现的位置,遍历整个字符串,若当前字符没有出现过,更新temp和pos数组对应位置的值,表示该字符在当前子串中已经出现过和出现的位置;若当前字母已经出现过了,则更新数组temp和pos的值,并将start移动到该字母上次出现的位置的后一位。
需要注意一点:在更新start前,要将start和字符上次出现的位置中间的那些字符的temp更新,表示那些字符在新的子串中还没有出现过。

代码:

class Solution {
public:
int lengthOfLongestSubstring(string s) {
        int maxnum = 0;
        int start = 0;
        int pos[256] = {-1};
        int temp[256] = {0};
        for(int i = 0;i<s.length();i++)
        {
            if(temp[s[i]-' '])
            {
                for(int j = start;j<pos[s[i]-' '];j++)
                temp[s[j]-' '] = 0;
                start = pos[s[i]-' ']+1;
                pos[s[i]-' '] = i;
            }
            else 
            {
                temp[s[i]- ' '] = 1;
                pos[s[i]-' '] = i;
            }
            if(i-start+1>maxnum)
            maxnum = i-start+1;

        }
        return maxnum;

    }
};

解法二:
还有一种解法是只用一个整型数组temp来表示每个字符出现的位置,遍历一遍字符串,当有字符的上次出现的位置大于start,表示该字符在子串中已经出现过一次了,这时更新start的值。每次循环都判断一下最大子串长度。这个解法的复杂度为O(n)。

代码:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int maxnum = 0;
        int start = -1;
        int l = s.length();
        int temp[256];
        memset(temp, -1, sizeof(temp));
        for(int i = 0;i<l;i++)
        {
            if(temp[s[i]-' ']>start)
            {
                start = temp[s[i]-' '];
            }
            if(i-start>maxnum) 
            {
                maxnum = i-start;
            }
            temp[s[i]-' '] = i;



        }
        return maxnum;

    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值