首页 > 其他 > 详细

【LeetCode】Longest Substring Without Repeating Characters

时间:2015-05-18 18:53:02      阅读:287      评论:0      收藏:0      [点我收藏+]

题目描述

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.

问题分析

这个题寻找最长的不重复字串,即在一个字符串里面,所有的字符都没有出现,可以定义个表,用来记录每一个字符第一次出现的位置,当发现有位置已经有字符了,将下表移动到index+1的位置,同时不断记录最长字串长度。
技术分享

代码

public class Solution {
   public int lengthOfLongestSubstring(String s) {
        if (s == null || s.length() == 0)
            return 0;
        int res = 1;
        boolean[] exist = new boolean[256];
        int start = 0;

        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (exist[ch]) {
                res = Math.max(res, i - start);
                for (int k = start; k < i; k++) {
                    if (s.charAt(k) == ch) {
                        start = k + 1;
                        break;
                    }
                    exist[s.charAt(k)] = false;
                }
            } else
                exist[ch] = true;
        }
        res = Math.max(res, s.length() - start);
        return res;

    }
}

总结

这个题并不算难,理解意思就会有思路的,只要能想到定义字符表基本上就能做出来

个人声明

本文章均为原创,转载请说明出处,谢谢
个人说明

本人对编程有很大兴趣,希望跟大家一起交流
欢迎访问个人论坛:www.dabenmo.com
如有任何问题请邮件:jianxiawzx@126.com

【LeetCode】Longest Substring Without Repeating Characters

原文:http://blog.csdn.net/jianxia_wzx/article/details/45825259

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!