3. Longest Substring Without Repeating Characters LeetCode题解
来源:互联网 发布:科比生涯平均数据 编辑:程序博客网 时间:2024/06/06 05:09
题目描述:
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.
题解:
考虑使用是个数组,记录每种字符最近一次出现的位置;
从字符串开始,计算以i位置结尾的最长无重复子串;
具体而言,需要使用另一个整型变量last记录最近一次重复字符的位置,每次更新last以及最大无重复长度;
Code【Java】
public class Solution { public int lengthOfLongestSubstring(String s) { // 处理特殊情况 if (s == null || s.length() == 0) { return 0; } // 记录最大长度 最近重复字符出现位置 int ans = 0; int last = 0; // 记录ASCII中字符 int[] hash = new int[256]; for (int i = 0; i < s.length(); ++i) { int index = (int)s.charAt(i); last = Math.max(last, hash[index]); hash[index] = i + 1; ans = Math.max(ans, i + 1 - last); } return ans; }}
Code【C++】
class Solution {public: int lengthOfLongestSubstring(string s) { // 特殊情况处理 if (s.size() == 0) { return 0; } // 记录结果 最近一次重复出现的位置 int ans = 0; int last = 0; // 使用数组存储每个字符最近一次出现的位置 int hash[256] = {0}; for (int i = 0; i < s.size(); ++i) { last = max(last, hash[s[i]]); ans = max(ans, i + 1 - last); hash[s[i]] = i + 1; } return ans; }};
0 0
- LeetCode题解:Longest Substring Without Repeating Characters
- LeetCode题解:Longest Substring Without Repeating Characters
- Leetcode题解:Longest Substring Without Repeating Characters
- [LeetCode]Longest Substring Without Repeating Characters题解
- LeetCode题解--3. Longest Substring Without Repeating Characters
- 3. Longest Substring Without Repeating Characters : LeetCode 题解
- Leetcode题解(Python): 3.Longest Substring Without Repeating Characters
- LeetCode题解:3. Longest Substring Without Repeating Characters
- leetcode 题解 3. Longest Substring Without Repeating Characters
- Leetcode题解 - 3. Longest Substring Without Repeating Characters
- LeetCode Algorithms 3. Longest Substring Without Repeating Characters 题解
- leetcode题解-3. Longest Substring Without Repeating Characters
- 3. Longest Substring Without Repeating Characters LeetCode题解
- LeetCode题解(Week 16):3. Longest Substring Without Repeating Characters
- LeetCode 3. Longest Substring Without Repeating Characters题解python
- Leetcode题解-3. Longest Substring Without Repeating Characters
- 3. Longest Substring Without Repeating Characters题解
- [LeetCode]3.Longest Substring Without Repeating Characters
- Spring Boot 基于注解的 Redis 缓存使用
- Tangram 的基础 —— vlayout(Android)
- 泛型的使用及注意点
- 20170506@Iterator迭代器
- [ReactNative] 03--ReactNative的生命周期 & render的Diff算法 & 组件之间的通信
- 3. Longest Substring Without Repeating Characters LeetCode题解
- Material Design之使用Toolbar
- Hibernate第三篇【主配置文件、映射文件、复合主键映射】
- Linux支持文件系统与VFS
- Spring整合MongoDB实现多个or的范围查询
- 记腾讯的暑期实习面试
- Java 使用包(Package)管理Java中的类
- 游戏同步策略
- 2017算法课.11(3Sum Closest)