[LeetCode]003. Longest Substring Without Repeating Characters

本文介绍了一种高效算法来找出给定字符串中最长的不包含重复字符的子串长度。通过使用两个指针和布尔数组标记字符是否唯一,算法能在O(n)时间内解决问题,并提供了Java和Python的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.


Solution: (reference:http://leetcode.com/2011/05/longest-substring-without-repeating-characters.html)

Running time: O(n), worst case---start and end both move n steps, o(2n).

use two indices to find the substring, the length can be (end-start), 

use boolean[] to mark the character whether is unique,

update the maxlen when we find a repeated character,

don't forget to update the maxlen after the while loop.


java中数组使用new 关键字分配空间后会赋默认值,默认值的值要看数组的类型。boolean[] 默认值为false.

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        // Start typing your Java solution below
        // DO NOT write main() function
        boolean[] visited = new boolean[256];
        int len = s.length();
        int start = 0;
        int end = 0;
        int maxlen = 0;
        while(end < len){
            if(!visited[s.charAt(end)]){
                //don't use s[end], because s is string , not char[] 
                visited[s.charAt(end)] = true;
                end++;
            }else{
                maxlen = Math.max(maxlen, end-start);
                while(s.charAt(start) != s.charAt(end)){
                    //don't forget this step, which is used to find new start 
                    visited[s.charAt(start)] = false;
                    start++;
                }
                start++;
                end++;
            }
        }
        maxlen = Math.max(maxlen, len-start);
        //if there is no repeated characters in an entire string 
        return maxlen;
    }
}


2015-03-14更新:

Python Solution:

Running Time: O(n).

class Solution:
    # @return an integersssss
    def lengthOfLongestSubstring(self, s):
        subStr = ''
        start = 0
        maxLen = 0
        for end in xrange(len(s)):
            if s[end] not in subStr:
                subStr += s[end]
            else:
                maxLen = max(maxLen, len(subStr))
                while s[start] != s[end]:
                    start += 1
                start += 1
                subStr = s[start:end+1]
        return max(maxLen, len(subStr))
        



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值