前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >Sliding Window - 3. Longest Substring Without Repeating Characters

Sliding Window - 3. Longest Substring Without Repeating Characters

作者头像
ppxai
发布2020-09-23 17:18:22
发布2020-09-23 17:18:22
31000
代码可运行
举报
文章被收录于专栏:皮皮星球皮皮星球
运行总次数:0
代码可运行

3. Longest Substring Without Repeating Characters

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.

思路:

求字符串中最长不重复的字串,可以用一个hashmap来保存字符出现的下标,key是字符,value是下标(加一,这样是为了保证aab这种连续情况不会重复),应为这里key是单个字符所以可以用一个array代替,然后用两个指针,一个记录不重复字符开始位置,一个去探索字符串。

代码:

java:

代码语言:javascript
代码运行次数:0
运行
复制
class Solution {

    public int lengthOfLongestSubstring(String s) {
        if (s == null || s.length() == 0) return 0;
        int[] map = new int[256];
        int max = 0, start = 0;
        char[] strs = s.toCharArray();
        for (int i = 0; i < strs.length; i++) {
            if(map[strs[i]] > 0) {
                //already exist
                start = Math.max(start, map[strs[i]]);
            }
            map[strs[i]] = i + 1;   
            max = max > i- start + 1 ? max : i- start + 1;
        }
        
        return max;
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019年07月14日,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

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