Longest-Substring-Without-Repeating-Characters


title: Longest Substring Without Repeating Characters
date: 2017-10-24 22:58:49
categories:
- algorithm
tags:

- algorithm

摘要:Brute Force

正文:
Sahara

Approach #1 Brute Force [Time Limit Exceeded]

第一眼看到 求最长的非重复子串,就是三个for循环 求解,去掉非法的判断,花了十分钟得到了一个不得使用“蛮力”,时间复杂度O(n*3)可是明明用了hashSet的Contain()方法了,Exception代码如下:

class Solution {
        public static boolean allUnique(String string,int start,int end){

        Set<Character> set =new HashSet<Character>();
        for (int i = start; i < end; i++){
            if (set.contains(string.toCharArray()[i])){
                return false;
            }
            set.add(string.toCharArray()[i]);
        }

        return true;
    }
    public int lengthOfLongestSubstring(String s) {
        int length = s.length();
        int ans = 0;
        for (int i = 0; i < length; i++){
            for (int j = i + 1; j <= length; j++){
                if (allUnique(s, i, j)){
                    ans = Math.max(ans, j - i);
                }
            }
        }
        return ans;
    }

}

看了别人通过的代码才知道我的暴力破除的确不够优雅啊 ,奉上正确的代码,很简单就不注释了

public int lengthOfLongestSubstring(String s) {
    if (s.length()==0) return 0;
    HashMap<Character, Integer> map = new HashMap<Character, Integer>();
    int max=0;
    for (int i=0, j=0; i<s.length(); ++i){
        if (map.containsKey(s.charAt(i))){
            j = Math.max(j,map.get(s.charAt(i))+1);
        }
        map.put(s.charAt(i),i);
        max = Math.max(max,i-j+1);
    }
    return max;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值