算法练习笔记(十六)—— 最长的子串

在leetcode上面练习题目的时候,经常会有子串(subsequence)和子集(substring)的区别,区分就在于子串总是连续的,而子集可以是字符串内任意字符的组合

题目:Longest Substring Without Repeating Characters

地址:https://leetcode.com/problems/longest-substring-without-repeating-characters/#/description

描述:

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.

解析:

由于对于时间复杂度没有太高的要求,因此我们可以直接遍历

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int len = s.size();
        if(len < 2)return len;
        int key = 1;
        for(int i = 0; i < len - 1; i ++){
            if(s[i] != s[i + 1]){
                int count = 2;      
                for(int j = i + 2; j < len; j ++){
                    int flag = 0;
                    for(int k = 1; k <= count; k ++){
                        if(s[j - k] == s[j])break;
                        if(k == count)flag = 1;
                    }
                    if(flag == 0)break;
                    count++;
                }
                key = max(key, count);
            }
        }
        return key;
    }
};


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值