Leetcode1-50: 03, Longest Substring Without Repeating Characters

Leetcode1-50: 03, Longest Substring Without Repeating Characters

问题描述

Given a string, find the length of the longest substring without repeating characters.

Example 1:

Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc", with the length of 3. 

Example 2:

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: "pwwkew"
Output: 3
Explanation: 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.

这一题大概意思是输入一个字符串,返回其中最长的没有重复元素的子串的长度

解题思路

sliding window

使用sliding window找出最大的不重复的window, 查找时通过HashMap来看是否存在重复元素

字典法

建立一个字典数组,保存字符出现的最后位置,这样就可以免去HashMap的查找操作,虽然时间复杂度没有提升,但是空间复杂度变成了常数O(1).(数组的长度对于字母是26,对于ASCII码是128,etc.)

代码实现

implement 1

public int lengthOfLongestSubstring(String s) {
        //if(s == null || s.length() == 0) return 0;
        HashMap<Character, Integer> hash = new HashMap<>();
        int ans = 0;
        for(int i = 0, j = 0; j < s.length(); j++) {
            char c = s.charAt(j);
            if(hash.containsKey(c)) {
                i = Math.max(i, hash.get(c));
            }    
            ans = Math.max(ans, j - i + 1);
            //注意这里很容易写成 hash.put(c, j),重复时需要记录的不是第一个出现的位子,而是第一个不与当前字母相同的位置 所以是j+1
            hash.put(c, j+1);        
        }
        return ans;
    }

在这里插入图片描述

implement 2

public int lengthOfLongestSubstring(String s) {
int n = s.length(), ans = 0;
int[] index = new int[128]; // current index of character
// try to extend the range [i, j]
for (int j = 0, i = 0; j < n; j++) {
i = Math.max(index[s.charAt(j)], i);
ans = Math.max(ans, j - i + 1);
index[s.charAt(j)] = j + 1;
}
return ans;
}

复杂度分析

HashMap的查找操作的时间复杂度是O(1), 所以程序的时间复杂度是O(n), 空间复杂度是O(n)

分析

前三题都比较简单,第一天的记录也到这。刷题的作用是需要记住算法的思想,遇到类似问题的时候也能够知道怎么去解决。例如题目中用的sliding window, 其实本身的用法有很多,但是遇到问题有时候就容易联系不上,所以还是得多练习反思才能巩固

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值