算法分析与设计——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.

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
       
};

思路


从左到右遍历,每个字母都与从head到它本身的所有字母比较是否相同,如果相同,则说明当前的substring已经不能再扩大了,将其长度与当前最大值取最大,并且将head直接移动到与当前字母(i)相同的字母(j)处的下一个,这样可以尽可能的减少重复的比较,因为上一个head第j个字母之间的每个字母作为head,到第i个字母时都会因为第j个字母的相同而使substring无法扩大,substring都小于上一个head到第i个字母。假设string长度为n,第一个循环将进行n次,第二个循环次数不会超过26(若全为小写)。

代码

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int head = 0, max = 0, current = 0;
        int size = s.size();
        int i, j;
        for (i = 0; i < size; i++) {
            for (j = head; j < i; j++) {
                if (s[j] == s[i]) {
                    break;
                }
            }
            if (j == i) {
                current++;
            } else {
                if (current > max) {
                    max = current;
                }
                current = current-(j-head);//从新的head到当前字母位置的substring的长度
                head = j+1;//移动head
            }
        }
        if (current > max) {
            max = current;
        }
        return max;
    }
};


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值