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

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

题目:3. Longest Substring Without Repeating Characters

要求:

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.

Subscribe to see which companies asked this question.

思路:

首先解释每个数据的意义:

ans为最终的结果,left表示我们最终子串最左边的字母在string s中的位置
last数组表示所检测的字母的上一次出现时在string s中的位置
然后思路就很清晰了
先对last数组赋值,全部置为-1,表示之前都没出现过
然后进行遍历
如果:该字母上一次出现时在left的后面(last[s[i]] >= left),表示该字母已经出现过了,重复了
那么:left就赋值为这个字母上一次出现的位置的下一位
否则:表示该字母就是第一次出现,left不用动,但是这个字母在string s 中就有位置了,得赋值,也就是i
最后:比较ans 和 i - left + 1的大小
然后return 就好


代码:

class Solution {public:    int lengthOfLongestSubstring(string s) {        int ans = 0;        int left = 0;        int last[255];        memset(last, -1, sizeof last);        for (int i = 0; i < s.length(); i++)        {            if (last[s[i]] >= left)            {                left = last[s[i]] + 1;            }            last[s[i]] = i;            ans = max(ans, i - left + 1);        }        return ans;    }};

转载于:https://www.cnblogs.com/lantx/p/7497784.html

你可能感兴趣的文章
Intellijidea建javaWeb以及Servlet简单实现
查看>>
thinkphp执行流程
查看>>
keepalived双机热备实现故障时发送邮件通知
查看>>
leetCode-Maximum Average Subarray I
查看>>
Hdu - 3999- The order of a Tree
查看>>
[译]Python面试中8个必考问题
查看>>
Swift 实现iOS Animation动画教程
查看>>
每天CookBook之JavaScript-078
查看>>
redux-form的学习笔记二--实现表单的同步验证
查看>>
JS 笔记
查看>>
[UVa 10603] Fill
查看>>
VS2015大括号高亮显示的设置方法
查看>>
selenium中js定位
查看>>
洛谷P1494 [国家集训队]小Z的袜子
查看>>
第七届蓝桥杯省赛--分小组
查看>>
MySQL5.5(cmake)简介、安装、应用、账户授权、还原、备份、还原
查看>>
使用PreparedStatement 查询一条数据 封装成一个学生的Student1对象
查看>>
Android dispatchTouchEvent
查看>>
CentOS上安装GlassFish4.0
查看>>
Period(sdut2476)
查看>>