【c++&leetcode个人刷题】(#3 Longest Substring Without Repeating Characters(无重复字符的最长子串))

【c++&leetcode个人刷题】(#3 Longest Substring Without Repeating Characters(无重复字符的最长子串))

Longest Substring Without Repeating Characters

Given a string s, find the length of the longest substring without repeating characters.

Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is “abc”, with the length of 3.

Example 2:
Input: s = "bbbbb"
Output: 1
Explanation: The answer is “b”, with the length of 1.

Example 3:
Input: s = "pwwkew"
Output: 3
Explanation: The answer is “wke”, with the length of 3.
Notice that the answer must be a substring, “pwke” is a subsequence and not a substring.

Example 4:
Input: s = ""
Output: 0

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters

思路

对于这题,我的思路也是穷举法
首先新建一个hash数组,用来存储每个字符串对应的不连续长度
如:abcabcbb,
s[0]开始最长连续为3,即“abc”
s[1]开始最长连续为3,即“bca”
.
.
s[7]开始最长连续为1,即“b”
所以hash数组为[3 3 3 3 2 3 1 1 ]
最后输出hash表中最大的数即可。

然后这么想有两个问题

  • 1.怎么判断连续不等
  • 2.计算太复杂,如:“abc”最长连续不等了,那么我们“bc”的连续不等就没必要再判断一次了(事实证明确实超时了)

至于问题1,我条件反射的想到两种方法:

  • 1.从 **s[i]s[i+j-1]进行循环,判断与s[i+j]**的字符串是否相等
  • 2.用find函数判断

至于问题2,我们可以把字符串的选取想象成滑动的,定义连续不重复字符串的start和end,最后只要计算start和end之间的距离。

如果在start和end之间的字符串不重复,那么end往后移一位

如果在start和end之间有字符串重复,那么start移动到重复的字符串后者位置(因为之前的组合肯定更短)

直到end达到原字符串尾部

于是程序就有:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int length = s.length();
        if(length==0) return 0;
        int start(0),end(0),max_length(0),local_length(0);
        int index;
        while(end<length){
            char cmp=s[end];
            for(index=start;index<end;index++){
                if(cmp==s[index]){
                    start=index+1;
                    local_length=end-start;
                    break;
                }
            } 
            end++;
            local_length++;
            max_length=max(local_length,max_length);
        }
        return max_length;
    }
};

如有错误,欢迎指正

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值