Leetcode 3 Longest Substring Without Repeating Characters

Longest Substring Without Repeating Characters

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.

Solution1

  • 最简单的方法莫过于暴力搜索了。从字符串中的第一个字符开始,往后搜索,直到找到一个字符与已搜索过的字符相同,然后再把第一个指针往后挪一个位置。重复该过程。代码实现如下:
import java.util.HashSet;
public class Solution {
    public int lengthOfLongestSubstring(String s) {
        HashSet<Character> temp = new HashSet<Character>();
        int result = 0;
        for(int i=0,j=0;i<=j&&j<s.length();){
            char c = s.charAt(j);
            if(!temp.contains(c)){
                if(j==s.length()-1) result = Math.max(result,j-i+1);//这里是防止在末尾的时候程序直接跳出了而没有处理
                temp.add(c);
                j++;
            }else{
                result = Math.max(result,j-i);
                if(j==s.length()-1) break;
                temp.remove(s.charAt(i++));//这里是将第一个指针往后挪一个
            }
        }
        return result;
    }
}

这种方法的时间复杂度为O( n2 ),空间复杂度为O( n <script type="math/tex" id="MathJax-Element-27">n</script>),其实这样已经很不划算了。

Solution2

  • 解法一的时间主要耗在每次有重复字符的时候,都必须将两个字符中间的字符再去遍历一次,这样便浪费了很多时间。另一种方法是只遍历一次字符串,每次都记录字符的位置,如果有重复的字符则更新该字符的位置,另外也更新计算子串长度的起始点。时间复杂度为O(n),空间复杂度也为O(n).代码如下:
import java.util.HashMap;
public class Solution {
    public int lengthOfLongestSubstring(String s) {
        HashMap<Character,Integer> temp = new HashMap<Character,Integer>();
        int result = 0;
        for(int i=0,start=0;i<s.length();i++){
            char c = s.charAt(i);
            if(temp.containsKey(c)) start = Math.max(start,temp.get(c)+1);//这里是要取二者之间的最大值。例如"abba"的时候
            result = Math.max(result,i-start+1);
            temp.put(c,i);
        }
        return result;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值