3. Longest Substring Without Repeating Characters 无重复字符的最长子串

这题思路很简单,滑动窗口并不复杂,数据结构用到Hashtable。
答案中写的比较好的是用Math.Max代替了我代码中的if。

3. Longest Substring Without Repeating Characters

https://leetcode.com/problems/longest-substring-without-repeating-characters/

Description

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.

Solutions

由于看到标签是hashtable、双指针、滑动窗口,就……思路很简单,就遍历一遍。用hashtable存起来字符和字符的位置,设置滑动窗口的起始位置,往后遍历。

Submissions

我的~

import java.util.Hashtable;
class Solution {
    public int lengthOfLongestSubstring(String s) {
        Hashtable hashchar = new Hashtable();
        //滑动窗口开始的位置
		int before=0;
        //最长子串的长度
		int res=0;
        for(int i=0;i<s.length();i++)
        {
            char temp=s.charAt(i);
        	//如果重复则滑动窗口往前滑一位,并保证查找的是滑动窗口之后的字符的位置
            if(hashchar.containsKey(temp)&&(int)hashchar.get(temp)>=before)
            	before=(int) hashchar.get(s.charAt(i))+1; 
            //加入哈希表,如果重复则覆盖掉,所以哈希表中都是滑动窗口以后的元素
            hashchar.put(s.charAt(i),i);
            //记录最长子串的长度
        	if((i-before+1)>res)
        		res=i-before+1;
        }
        return res;
    }
}

可以看到,我用hashtable来做应该直接就是方法三:优化的滑动窗口。
它用Math.Max代替了我代码中的if,以及i和j都往后推了一位来表示。
https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/solution/wu-zhong-fu-zi-fu-de-zui-chang-zi-chuan-by-leetcod/

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length(), ans = 0;
        Map<Character, Integer> map = new HashMap<>(); // current index of character
        // try to extend the range [i, j]
        for (int j = 0, i = 0; j < n; j++) {
            if (map.containsKey(s.charAt(j))) {
                i = Math.max(map.get(s.charAt(j)), i);
            }
            ans = Math.max(ans, j - i + 1);
            map.put(s.charAt(j), j + 1);
        }
        return ans;
    }
}

Summary

遇到的错误:

  1. if判断中的条件需要是个boolean类型,里面条件写长了写着写着就忘了,写了个int还没和before进行比较就开始焦虑哪里错了,其实就是没写完,而且思路不清晰。
  2. error: cannot find symbol
    如何排查can not find symbol的编译错误
    Hashtable这里报错
    leetcode也要import啊
    import java.util.Hashtable;
  3. 以我的表面观察,hashmap和hashtable的区别就是map要声明好object的类型,而table不用?
  4. 取出来的位置(Object)需要cast成(int)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值