当前位置:网站首页>The sword refers to offer 48: the longest non-repeating substring
The sword refers to offer 48: the longest non-repeating substring
2022-07-30 09:12:00 【brave little yao】
Title description:
Please find the longest substring that does not contain repeated characters from the string, and calculate the length of the longest substring.
Example 1:
Enter: "abcabcbb"
Output: 3
Explanation: Since the longest substring without repeating characters is "abc", its length is 3.
Example 2:
Enter: "bbbbb"
Output: 1
Explanation: Since the longest substring without repeating characters is "b", its length is 1.
Example 3:
Enter: "pwwkew"
Output: 3
Explanation: Since the longest substring without repeating characters is "wke", its length is 3.
Please note that your answer must be the length of the substring, "pwke" is a subsequence, not a substring.
Solution 1: Sliding window
Ideas:
First, left and right point to the head of the window at the same time, and the right window keeps moving to the right. Use Set to maintain a non-repetitive sliding window. When encountering duplicate elements, immediately move the left window to remove duplicates, and record the window empty at this time.length.The previous steps are then repeated until the window has traversed all elements.
Code:
class Solution {public int lengthOfLongestSubstring(String s) {int res = 0;Set set = new HashSet<>();for(int l = 0, r = 0; r < s.length(); r++) {char c = s.charAt(r);while(set.contains(c)) {set.remove(s.charAt(l++));}set.add(c);res = Math.max(res, r - l + 1);}return res;}} Solution 2: Double-ended queue
Ideas:
Use a double-ended queue as a sliding window. When encountering an existing number in the queue, delete it from the head of the queue (until the existing number is deleted), otherwise add elements from the end of the queue
Code:
class Solution {public int lengthOfLongestSubstring(String s) {Deque deque = new ArrayDeque<>();int max=0;for (int i = 0; i < s.length(); i++) {if (!deque.contains(s.charAt(i))) {deque.addLast(s.charAt(i));}else {max = Math.max(max, deque.size());while(deque.peekFirst()!=s.charAt(i)) {deque.removeFirst();}deque.removeFirst();deque.addLast(s.charAt(i));}}max = Math.max(max, deque.size());return max;}} 边栏推荐
猜你喜欢
随机推荐
函数(1)
C语言力扣第46题之全排列。回溯法
SQL injection vulnerability (postgresql injection)
One article to understand twenty kinds of switching power supply topologies
npm指令
typescript5-编译和安装ts代码
【无标题】
【愚公系列】2022年07月 Go教学课程 021-Go容器之切片操作
leetcode经典问题——11.盛水最多的容器
OA Project Pending Meeting & History Meeting & All Meetings
【蓝桥杯选拔赛真题45】Scratch猫鼠游戏 少儿编程scratch蓝桥杯选拔赛真题讲解
js currying
信号完整性测试
test3
test2
基于SSM实现个性化健康饮食推荐系统
typescript2-typescript为什么给js添加类型支持
Hands-on teaching OneOS FOTA upgrade
用示波器揭示以太网传输机制
【Flask框架②】——第一个Flask项目









