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) {
        
    }
};

如题所示:要求找出不含有重复字母的最长字串。

解决方法:建立两个下标ij,分别对应当前子串的起始位置和终点位置,j从0开始向右移动。

在检索过所有的字符,即j=s.length()的时候,停止扫描。

此外,需要设置一个256大小的数组exist用于存储出现在当前子串的字符。

流程如下:

1.判断当前字符s[j]是否已经出现在当前子串中。

2.若不出现在当前子串中,则将该字符对应的在exit数组中的ASCII码下标设置为true,并将j向右移动一个单位,最大长度maxLen加1。

3.若出现在当前子串中,则需要将起始位置i移至该字符第一次出现的位置处,并将之前的字符在exit数组中的对应位置设为false,由于需要寻找新的子串,所以需要将i和j都向右移动一个单位。最后再比较maxLen和当前子串长度j-i的大小,并将maxLen更新为其中较大者。

代码实现如下:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
    	int i=0,j=0;
    	int maxLen = 0;
    	bool exist[256]={false};
    	while(j<s.length()){
    		if(!exist[s[j]]){
    			exist[s[j]]=true;
    			j++;
    		}else{
    			while(s[i]!=s[j]){
    				exist[s[i]]=false;
    				i++;
    			}
    			i++;
    			j++;
    		}
    		maxLen = maxLen > j-i ? maxLen:j-i;
    	}
    	
        return maxLen;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值