当前位置:网站首页>Longest substring without repeated characters (Sword finger offer 48)
Longest substring without repeated characters (Sword finger offer 48)
2022-06-27 14:22:00 【input_ out】
The longest substring without repeating characters ( The finger of the sword Offer 48)
1 Problem description
Please find the longest substring in the string that does not contain duplicate characters , Calculate the length of the longest substring .
Input : "abcabcbb"
Output : 3
explain : Because the longest substring without repeating characters is "abc", So its length is 3.
2 Their thinking
The length is N Shared string (n+1)n/2 The traversal complexity of the substring is O(n²), Judge the length as N The complexity of whether the string has duplicate characters is O(N) , Therefore, the complexity of using violence to solve this problem is O(n³).
First thought of using HashSet Reduce , Judge the length as N The complexity of whether the string has duplicate characters is O(1), towards set Add , return false There is repetition . So use double cycle plus HashSet The time complexity of solving the problem is O(n²).
thought : The first layer iterates through the string , from s[i]( Starts 0) Start , Second layer circulating feed s[i+1] Began to set Add elements to it , If returns flase, Record the current set The size is the length of the non repeating substring , And empty set Exit the second loop , use sum preservation set The maximum size . Enter the next cycle from i+1 Start judging .
class Solution {
public int lengthOfLongestSubstring(String s) {
if(s.equals("")||s==null){
return 0;
}
int sum=0;
Set<Character> set = new HashSet<>();
for(int i = 0;i<s.length();i++){
set.add(s.charAt(i));
for(int j = i+1;j<s.length();j++){
if(!set.add(s.charAt(j))){
sum=Math.max(sum,set.size());
set.clear();
break;
}
}
sum=Math.max(sum,set.size());
}
return sum;
}
}
3 improvement
The time complexity of using violence is too large , Therefore, we can consider using dynamic programming to reduce the time complexity . The main problem is to find the distance between two identical characters that are farthest apart , Consider using HashMap Save the subscript of each character , When traversing to the same character, the distance between them is saved and updated HashMap, Finally, return the maximum value of the distance saved each time .
State definition : Set up a dynamic programming list dp ,dp[j] Represents with the character s[j] For the end of “ The longest non repeating substring ” The length of .
Transfer equation : Fixed right border j , Set character s[j] The same character nearest to the left is s[i] , namely s[i] = s[i]=s[j] .
When i<0 , namely s[j] There is no same character on the left , be dp[j] = dp[j-1] + 1;
When dp[j−1]<j−i , Describe the previous and s[i] The same characters are not included in this time s[i] Substring of dp[j-1] in , be dp[j] = dp[j - 1] + 1 ;
When dp[j−1]≥j−i , Describe the previous and s[i] Want the same characters to contain s[i] Substring of dp[j−1] In the interval , be dp[j] The left boundary of is bounded by s[i] decision , namely dp[j] = j - i;
Finally back to max(dp).
Because the return value is dp List maximum , So with the help of variables tmp Storage dp[j] , Variable res Update the maximum value of each round .
class Solution {
public int lengthOfLongestSubstring(String s) {
if(s.equals("")||s==null){
return 0;
}
int temp = 0;
int res = 0;
HashMap<Character,Integer> map = new HashMap<>();
for(int i = 0;i<s.length();i++){
int j = map.getOrDefault(s.charAt(i),-1);
map.put(s.charAt(i),i);
if(temp<i-j){
temp++;
}else{
temp = i-j;
}
res = Math.max(res,temp);
}
return res;
}
}
边栏推荐
- 剑指 Offer II 039. 直方图最大矩形面积 单调栈
- Four characteristics of transactions
- How to select cross-border e-commerce multi merchant system
- EventLoop learning
- [OS command injection] common OS command execution functions and OS command injection utilization examples and range experiments - based on DVWA range
- Integration of entry-level SSM framework based on XML configuration file
- 隐私计算FATE-离线预测
- AcWing 第57 场周赛
- Can flush open an account for stock trading? Is it safe?
- 美国芯片再遭重击,继Intel后又一家芯片企业将被中国芯片超越
猜你喜欢

What is the difference between the FAT32 and NTFS formats on the USB flash disk

CMOS级电路分析
![[WUSTCTF2020]girlfriend](/img/a8/33fe5feb7bcbb73ba26a94d226cc4d.png)
[WUSTCTF2020]girlfriend

Redis master-slave replication, sentinel mode, cluster cluster
![[business security 03] password retrieval business security and interface parameter account modification examples (based on the metinfov4.0 platform)](/img/29/73c381f14a09ecaf36a98d67d76720.png)
[business security 03] password retrieval business security and interface parameter account modification examples (based on the metinfov4.0 platform)

Tsinghua & Shangtang & Shanghai AI & CUHK proposed Siamese image modeling, which has both linear probing and intensive prediction performance

Kyndryl与Oracle和Veritas达成合作

隱私計算FATE-離線預測

Step by step expansion of variable parameters in class templates

Leetcode 724. 寻找数组的中心下标(可以,一次过)
随机推荐
招标公告:暨南大学附属第一医院Oracle数据库维保服务采购
Principle Comparison and analysis of mechanical hard disk and SSD solid state disk
Kyndryl与Oracle和Veritas达成合作
为什么 Oracle 云客户必须在Oracle Cloud 季度更新发布后自行测试?
my.ini文件配置
American chips are hit hard again, and another chip enterprise after Intel will be overtaken by Chinese chips
Summary of basic usage of command line editor sed
国产数据库乱象
A brief analysis of the differences between domestic and foreign e-commerce
Interpretation of new version features of PostgreSQL 15 (including live Q & A and PPT data summary)
In the past, domestic mobile phones were arrogant in pricing and threatened that consumers would like to buy or not, but now they have plummeted by 2000 for sale
Redis 主从复制、哨兵模式、Cluster集群
Library management system
[WUSTCTF2020]girlfriend
PCL Library - error reporting solution: cmake and Anaconda conflicts during installation
Four characteristics of transactions
Number of printouts (solved by recursive method)
易周金融 | Q1手机银行活跃用户规模6.5亿;理财子公司布局新兴领域
Openssf security plan: SBOM will drive software supply chain security
Practice of constructing ten billion relationship knowledge map based on Nebula graph