【刷leetcode,拿Offer-017】3. Longest Substring Without Repeating Characters(字符串+思维)

39 篇文章 0 订阅
39 篇文章 0 订阅

##3. Longest Substring Without Repeating Characters
Description:
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.

####题意:
求最长不重复子串(非子序列)。

####解题:
求无重复字符,也就是说最终选出的字符串中没有重复的字符(好吧,像是废话),那么最大长度是什么呢?
是每一个字符和其上一个出现位置之间的距离的最大值吗?显然不对,因为我们无法保证,这段区间内没有其他重复字符,我们应当保证每个字符都处在合法的位置,即该字符所在位置往后至当前遍历检查的位置之间没有其他任何重复字符。那么如何实现呢?即一旦出现了重复字符,就将每个字符ch的位置pos更新为max(pos[ch],pos[i]),其中pos[ch]表ch字符的原位置,pos[i]表当前字符的原位置。故而这两个值中的最大值往后至当前是肯定没有重复字符的。故每次只要求max(i-pos[ch],res)的最大值即可。解法一:

int lengthOfLongestSubstring(string s) {
        int pos[256],ch,res=0,tmp;
        for(int i=0;i<256;i++)
            pos[i]=-1;
        for(int i=0;i<s.length();i++)
        {
        	ch=s[i];
        	tmp=i-pos[ch];
        	if(tmp>res)
        	  res=tmp;
            if(pos[ch]==-1)
            {
              pos[ch]=i;
            }
            else
            {
              for(int j=0;j<256;j++)
                 if(j!=ch)
                  pos[j]=max(pos[ch],pos[j]);
              pos[ch]=i;
            }
        }
        return res;
    }

解法二:但仔细观察就可以发现,不用单独维护每个字符的合法位置,可以用每个字符的最大合法位置来更新一个全局最优的位置,也就除去了解法一更新每个字符256循环的过程。

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
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值