博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 3. Longest Substring Without Repeating Characters
阅读量:6939 次
发布时间:2019-06-27

本文共 1119 字,大约阅读时间需要 3 分钟。

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.

首先建立一个256位大小的整型数组来表示哈希表,定义两个变量res和left,res记录最长无重复子串的长度,left记录最长无重复子串的起始位置。

然后遍历该字符串,对于每一个遍历到的字符,如果哈希表中该字符对应的值为-1, 则说明没有遇到过该字符,此时将该字符加入到最长无重复子串中,长度为i - left + 1, i为遍历到字符的位置。

还有一种情况也需要记录,当哈希表中的值小于left,这是由于此时出现过重复字符,但是left的位置更新了。

c++代码

1 class Solution { 2 public: 3     int lengthOfLongestSubstring(string s) { 4         vector
hash(256, -1); 5 int left = 0; 6 int res = 0; 7 for(int i = 0; i < s.size(); ++ i) 8 { 9 if(hash[s[i]] == -1 || left > hash[s[i]])10 res = max(res, i - left + 1);11 else12 left = hash[s[i]] + 1;13 hash[s[i]] = i;14 }15 return res;16 }17 };

 

转载于:https://www.cnblogs.com/xjtuchenpeng/p/7724349.html

你可能感兴趣的文章
SpringMVC 架构、原理
查看>>
jsp中把js变量赋给java变量,或者将java变量赋给js变量怎么做
查看>>
Spring Shiro
查看>>
递归求组合数
查看>>
小蚂蚁学习数据结构(10)——树的基本介绍
查看>>
域环境迁移
查看>>
FastDFS安装使用实战一(安装篇)
查看>>
我的友情链接
查看>>
更改DEB包内容
查看>>
我的友情链接
查看>>
ibatis动态语句中的prepend
查看>>
keepalived实现LVS的高可用以及实现web服务的高可用(主从模型、双主模型)
查看>>
linux apache
查看>>
Mysql DBA 高级运维学习之路-删除表中数据
查看>>
4.26日第14次作业,23章项目整体绩效评估,24-32章信息安全相关知识
查看>>
新一代java模板引擎典范 Beetl
查看>>
centos6.8+nginx搭建简单的https服务器
查看>>
cut,sort,wc,uniq,tee,tr,split,并且,和,或者
查看>>
LVS负载均衡之三:LVS-DR搭建web群集、LVS结合Keepalived搭建高可用web群集
查看>>
JavaScript 堆内存分析新工具 OneHeap
查看>>