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 subsequenceand not a substring.

二、思路分析

基本思路是使用哈希,再使用指针,一个指针为start 指向当前遍历的字串的开始位置,如果遇到重复字符假如为t,就将 start的位置 改为上一个t所在位置+1. 另一个指针i指向当前长度为当前遍历的字串的位置,所以长度为i-start,并且用max时刻记着当前的最大长度。

例如:对于 “abcdbc” 初始 start=0, 当遍历到 第二个 b时,检测到重复。上一个b的位置是1. 因此 start=1+1。 然后还有更新 hash。

三、代码

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int hash[256];
        for(int i=0; i<256; i++) hash[i] = -1;
        int start = 0, max = 0;
        int i;
        for(i=0; i<s.size(); i++){
            if(hash[s[i]] != -1){
                if(max < i - start) {
                	max = i - start;	
                }
                for (int j = start; j < hash[s[i]]; j++) {
                	hash[j] = -1;	
                }
                if(hash[s[i]] + 1 > start )
                    start = hash[s[i]] +1;
            }
            hash[s[i]] = i;
        }
        if(max < i-start) {
		max = i-start;
	}
        return max;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值