LeetCode 3. Longest Substring Without Repeating Characters

题目描述:

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

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", 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.

Subscribe to see which companies asked this question.

解析:

求一个字符串中最大无重复子串长度的问题,比较直接的思路是用贪心的思想解决,即从第一个字符开始遍历,记录开始位置和每个字符的索引位置,当遇到重复字符时,则将其实位置更新为该字符的索引位置的下一个字符的位置,同时更新该字符的索引字符,计算该子串的长度Len。

需要注意边界情况,当字符串遍历到最后一个字符的时候,实际上最后一个无重复子串的长度是没有计算的,需要在循环外计算下最后一个无重复子串的长度。

这道题的一个难点在于如何记录每一个字符和所对应的索引位置,在python里直接用个字典结构就可以,在java里也能用hashmap之类的结构,不过懒得写了,就参考网上的方法,用了个数组记录,实际上也类似于hash的思想。

原始代码:

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int[] last=new int[128];
        for(int i=0;i<last.length;i++) last[i]=-1;
        int len=0;
        int start=0;
        char[] w = s.toCharArray();
        for(int i=0;i<w.length;i++){
        	if(last[w[i]-' '] >= start){
        		int temp=i-start;
        		if(temp>len)
        			len=temp;
        		start=last[w[i]-' ']+1;
        	}
        	last[w[i]-' ']=i;
        }
        if(w.length-start>len){
        	return w.length-start;
        }else{
        	return len;
        }
    }
}

总结:

这道题做的还是很顺利的,思路比较简单,只是觉得用动态规划解决应该更有锻炼意义些,这几天比较忙,等过一阵子补上。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值