当前位置:网站首页>"3 Longest Substring Without Repeating Characters" on the 17th day of LeetCode brushing
"3 Longest Substring Without Repeating Characters" on the 17th day of LeetCode brushing
2022-08-11 03:57:00 【small machine double】
LeetCode3 无重复字符的最长子串
Substring refers to substrings concatenated together,The subsequence don't have to get together every element,As long as the priority order of the elements is satisfied.例如:pwwkew,Its not repeat sequence can bewke,kew,But its non-repetitive subsequence can bepwke.
题目描述
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度.
示例
示例1:
输入:“abcabcbb"
输出:3
解释:解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3.
示例2:
输入:“bbbbb”
输出:1
解释:因为无重复字符的最长子串是 “b”,所以其长度为 1.
示例3:
输入: “pwwkew”
输出:3
解释:因为无重复字符的最长子串是 “wke”,所以其长度为 3.
提示:哈希表,双指针,字符串,Sliding Window(滑动窗口)
题目解析
According to the topic given,can be written using the sliding window trick,The sliding window technique itself is used to find some continuous extreme values in a string or array,For example the longest substring length here.The question now is when can we expand the size of the sliding window?很明显,When the next character is inconsistent with the character in the current sliding window,Should broaden its.And when should you reduce the size of the sliding window??when there is repetition,All elements to the left of the repeated characters in the sliding window should be deleted,In this process, as long as the maximum value of the sliding window is recorded, the correct answer can be obtained..
When the sliding window is implemented, the left and right pointers are generally used to define the boundary of the sliding window.,假设这里我们使用leftto represent the left border of the sliding window,rightto represent the right edge of the sliding window,The length of the sliding window is(right - left).Now turn the question into when to increaseleft(缩小窗口),when to increaseright(扩大窗口),The process is the same as described above.
解法一:
The code implementation can use some collection framework to save the array in the sliding window,This makes it easier for us to determine whether an element is in the sliding window,Of course we use an array to save,It is also possible to delete the data you want to delete after making your own judgment..使用set集合的代码如下:
class Solution {
public int lengthOfLongestSubstring(String s) {
if (s.length() == 0) {
return 0;
}
int maxLen = 0; //Record the maximum value of the sliding window
int left = 0, right = 0; //滑动窗口的左边界和右边界
Set<Character> set = new HashSet<>();
while (left < s.length() && right < s.length()) {
if (!set.contains(s.charAt(right))) {
//判断setWhether there are repeated characters in the set
set.add(s.charAt(right));
right++; //Sliding window elements and expanding the scope of the sliding window is added
maxLen = Math.max(maxLen, right - left);
} else {
set.remove(s.charAt(left)); //The characters in it will remove them one by one to the position of the repeating element
left++;
}
}
return maxLen;
}
}
程序的运行结果:
解法二:
其实上述setThe lookup done by the collection can be completely replaced by writing a loop ourselves,而且也比较好理解,代码如下:
class Solution {
public int lengthOfLongestSubstring(String s) {
if (s.length() == 0) {
return 0;
}
int maxLen = 1; //If the program is executed,则串s中至少有一个元素
int left = 0, right = 1;
while (right < s.length()){
int index = -1;
for (int j = right - 1; j >= left; j--) {
//模拟setThe process of collection to find elements,Find the subscript of the current recurring element from the back to the front
if (s.charAt(right) == s.charAt(j)) {
index = j;
break;
}
}
if (index != -1) {
left = index + 1; //The left border of the new window should be the next bit of the repeated element
}
right++;
maxLen = Math.max(maxLen, right - left);
}
return maxLen;
}
}
程序运行结果:It can be seen from the code that the worst time complexity should beO(n2)的,And the performance of traversal lookup is notsetGood performance for finding an element in a collection,Therefore, rather than usingsetThe way to gather is a lot slower.
解法三
At this point, we can already find that the key to solving this problem is how to quickly find the same element as the current traversed element from the elements in the existing sliding window.,The time complexity of the above two methods isO(logn)和O(n)级别.And a faster way to lookup is to use a hash table,It can be achieved without conflictO(1)的时间复杂度,快了很多.And the string given in the question is at most only256个,and there is no conflict,So it is possible to create a size of256的数组,Its subscript is the corresponding characterASCII码的值,**And the value stored in the array is the position of the last occurrence of the character(从1开始,Because the array is initially0,Saving index values may cause code to run incorrectly)**代码如下:
class Solution {
public int lengthOfLongestSubstring(String s) {
if (s.length() == 0) {
return 0;
}
int[] hash = new int[256];
int maxLen = 0;
int left = 0, right = 0;
while (left < s.length() && right < s.length()) {
char c = s.charAt(right);
left = Math.max(left, hash[c]); //Get the position of the last occurrence of the current character in the sliding window(This is equivalent to the above process,直接 使用O(1)The time complexity of
maxLen = Math.max(maxLen, right - left + 1);
hash[c] = ++right; //keep the position of the last occurrence of the element
}
return maxLen;
}
}
程序运行结果:
It can be seen that it is better to usesetSet almost doubled~
边栏推荐
- "110 Balanced Binary Tree Judgment" in leetCode's 14-day binary tree series
- 蹭个热度-请勿打开
- Unity2D animation (1) introduction to Unity scheme - animation system composition and the function of use
- What has programmatic trading changed?
- [FPGA] day19- binary to decimal (BCD code)
- AI+医疗:使用神经网络进行医学影像识别分析
- Interchangeability and Measurement Technology—Surface Roughness Selection and Marking Method
- Binary tree related code questions [more complete] C language
- Which one to choose for mobile map development?
- 荣威imax8ev魔方电池安全感,背后隐藏着哪些黑化膨胀?
猜你喜欢
Build Zabbix Kubernetes cluster monitoring platform
The last update time of the tables queried by the two nodes of the rac standby database is inconsistent
2022-08-10 The sixth group Hiding spring study notes
电力机柜数据监测RTU
Rotary array problem: how to realize the array "overall reverse, internal orderly"?"Three-step conversion method" wonderful array
【FPGA】day19-二进制转换为十进制(BCD码)
LeetCode Brush Questions Day 11 String Series "58 Last Word Length"
Graphical LeetCode - 640. Solving Equations (Difficulty: Moderate)
使用jackson解析json数据详讲
Description of ESB product development steps under cloud platform
随机推荐
Get the length of the linked list
typedef defines the structure array type
Differences and connections between distributed and clustered
Power Cabinet Data Monitoring RTU
C# 一周入门高级编程之《C#-LINQ》Day Four
MYSQLg advanced ------ clustered and non-clustered indexes
"98 BST and Its Verification" of the 13th day of leetcode brushing series of binary tree series
Leetcode 450. 删除二叉搜索树中的节点
leetcode刷题第13天二叉树系列之《98 BST及其验证》
shell监视gpu使用情况
元素的BFC属性
Audio codec, using FAAC to implement AAC encoding
DNS separation resolution and intelligent resolution
.NET自定义中间件
Paper Accuracy - 2017 CVPR "High-Resolution Image Inpainting using Multi-Scale Neural Patch Synthesis"
【愚公系列】2022年08月 Go教学课程 036-类型断言
The development of the massage chair control panel makes the massage chair simple and intelligent
LeetCode刷题第12天二叉树系列之《104 二叉树的最大深度》
多串口RS485工业网关BL110
A brief analysis of whether programmatic futures trading or manual order is better?