前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【每天一道编程系列-2018.2.16】(Ans)

【每天一道编程系列-2018.2.16】(Ans)

作者头像
yesr
发布2019-03-14 12:54:10
3140
发布2019-03-14 12:54:10
举报
文章被收录于专栏:leetcode_solutions

【题目描述】

  Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for “abcabcbb” is “abc”, which the length is 3. For “bbbbb” the longest substring is “b”, with the length of 1. 

【题目翻译】

给定一个字符串,找字符中的最大非重复子串 

【解题思路】

  用start记录当前处理的开始位置 历遍字符串,当当前字符从开始位置start开始已经出现过的时候,子串开始位置+1,否则更新map中的hash值为当前位置 

【本题答案】

代码语言:javascript
复制
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yesr
 * @create 2018-02-16 下午11:08
 * @desc
 **/
public class Test0216 {
    public int lengthOfLongestSubstring(String s) {
        if (s == null) {
            return 0;
        }

        int start = 0;
        int result = 0;
        Map<Character, Integer> map = new HashMap<>(s.length());

        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (map.containsKey(ch) && map.get(ch) >= start) {
                start = map.get(ch) + 1;
            }
            else {
                result = Math.max(result, i - start + 1);
            }

            map.put(ch, i);
        }
        return result;
    }

    public int lengthOfLongestSubstring2(String s) {
        if (s == null) {
            return 0;
        }

        int[] appear = new int[256];
        Arrays.fill(appear, -1);
        int start = 0;
        int result = 0;

        for (int i = 0; i < s.length(); i++) {
            if (appear[s.charAt(i)] >= start) {
                start = i + 1;
            }
            else {
                result = Math.max(result, i - start + 1);
            }
            appear[s.charAt(i)] = i;
        }

        return result;
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018年02月16日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档