[LeetCode] Longest Substring Without Repeating Characters

简介: Well, there many ways to solve this problem. Let's first look at a naive solution. The basic idea is simple.

Well, there many ways to solve this problem. Let's first look at a naive solution.

The basic idea is simple. Starting from the first character of the string, we visit the next character sequentially. If no duplicates appear, we count the length and update the maximum length. When we meet a repeated character, we find the position of its previous appearance (denoted as pre) and set the starting position to be pre + 1 and repeat the above process till the ending point has exceeded the length of the string. To implement this algorith, we need a hash table to record the last occurrence of each character we see and two pointers for the starting and ending position.

The code is as follows.

 1     // Naive implementation using two pointers
 2     int lengthOfLongestSubstring(string s) {
 3         int pos[256];
 4         memset(pos, -1, sizeof(pos));
 5         int start = 0, end = 0, maxlen = 0;
 6         while (end < (int)s.length()) {
 7             if (pos[s[end]] >= 0) {
 8                 maxlen = max(maxlen, end - start);
 9                 start = pos[s[end]] + 1;
10                 end = start;
11                 memset(pos, -1, sizeof(pos));
12             }
13             else pos[s[end]] = end++;
14         }
15         return max(maxlen, end - start);
16     }

I hope this code to be self-explanatory enough. In fact, we can see that the record of end is to obtain the length of the current substring. So we may simply use another variable to store the length directly. The code then becomes as follows.

 1     // Naive implementation using one pointer
 2     int lengthOfLongestSubstring(string s) {
 3         int pos[256];
 4         memset(pos, -1, sizeof(pos));
 5         int start = 0, len = 0, maxlen = 0;
 6         while (start < (int)s.length()) {
 7             if (pos[s[start]] >= 0) {
 8                 maxlen = max(maxlen, len);
 9                 start = pos[s[start]] + 1;
10                 memset(pos, -1, sizeof(pos));
11                 len = 0;
12             }
13             else {
14                 pos[s[start]] = start++;
15                 len++;
16             }
17         }
18         return max(maxlen, len);
19     }

Both of the above codes have called memset several times and thus take much time. In fact, only the characters after the new starting point (inclusive) need to be reset. So we can further reduce the amout of work. We can use a boolean arary to denote whether the element has been appeared and reset those after the new starting point (inclusive).

The following code runs much faster!

 1     int lengthOfLongestSubstring(string s) {
 2         bool exist[256] = {false};
 3         int start = 0, end = 0, maxlen = 0;
 4         while (end < (int)s.length()) {
 5             if (exist[s[end]]) {
 6                 maxlen = max(maxlen, end - start);
 7                 while (s[start] != s[end])
 8                     exist[s[start++]] = false;
 9                 start++;
10                 end++;
11             }
12             else exist[s[end++]] = true;
13         }
14         return max(maxlen, end - start);
15     }

One of my friend suggests the following code. It may be hard to understand for the first time. The trick is that it records the length of the current substring and updates it whenever a duplicate occurred.

 1     int lengthOfLongestSubstring(string s) {
 2         int pos[256];
 3         memset(pos, -1, sizeof(pos));
 4         int len = 0, maxlen = 0;
 5         for (int i = 0; i < s.length(); i++) {
 6             int pre = pos[s[i]];
 7             if (pre == -1 || i - len > pre)
 8                 len++;
 9             else {
10                 maxlen = max(maxlen, len);
11                 len = i - pre;
12             }
13             pos[s[i]] = i;
14         }
15         return max(maxlen, len);
16     }

Some nice people posted the following short DP code in the LeetCode discuss. The code is damn cool! Please refer to this link for more explanations.

 1     // Dynamic Programming
 2     int lengthOfLongestSubstring(string s) {
 3         int pos[256];
 4         memset(pos, -1, sizeof(pos));
 5         int start = 0, maxlen = 0;
 6         for (int i = 0; i < s.length(); i++) {
 7             start = max(start, pos[s[i]] + 1);
 8             maxlen = max(maxlen, i - start + 1);
 9             pos[s[i]] = i;
10         }
11         return max(maxlen, (int)s.length() - start);
12     }
目录
相关文章
Leetcode 516. Longest Palindromic Subsequence
找到一个字符串的最长回文子序列,这里注意回文子串和回文序列的区别。子序列不要求连续,子串(substring)是要求连续的。leetcode 5. Longest Palindromic Substring就是求连续子串的。
48 0
|
Java
Leetcode 3. Longest Substring Without Repeating Characters
此题题意是找出一个不包含相同字母的最长子串,题目给出了两个例子来说明题意,但这两个例子具有误导性,让你误以为字符串中只有小写字母。还好我是心机boy,我把大写字母的情况也给考虑进去了,不过。。。。字符串里竟然有特殊字符,于是贡献了一次wrong answer,这次我把ascii字符表都考虑进去,然后就没问题了。这个故事告诫我们在编程处理问题的时候一定要注意输入数据的范围,面试中可以和面试官去确认数据范围,也能显得你比较严谨。
50 3
|
算法 Python
LeetCode 1160. 拼写单词 Find Words That Can Be Formed by Characters
LeetCode 1160. 拼写单词 Find Words That Can Be Formed by Characters
LeetCode 1160. 拼写单词 Find Words That Can Be Formed by Characters
LeetCode 424. Longest Repeating Character Replacem
给你一个仅由大写英文字母组成的字符串,你可以将任意位置上的字符替换成另外的字符,总共可最多替换 k 次。在执行上述操作后,找到包含重复字母的最长子串的长度。
104 0
LeetCode 424. Longest Repeating Character Replacem
LeetCode 409. Longest Palindrome
给定一个包含大写字母和小写字母的字符串,找到通过这些字母构造成的最长的回文串。 在构造过程中,请注意区分大小写。比如 "Aa" 不能当做一个回文字符串。
74 0
LeetCode 409. Longest Palindrome
|
2月前
|
Unix Shell Linux
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
本文提供了几个Linux shell脚本编程问题的解决方案,包括转置文件内容、统计词频、验证有效电话号码和提取文件的第十行,每个问题都给出了至少一种实现方法。
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
|
3月前
|
Python
【Leetcode刷题Python】剑指 Offer 32 - III. 从上到下打印二叉树 III
本文介绍了两种Python实现方法,用于按照之字形顺序打印二叉树的层次遍历结果,实现了在奇数层正序、偶数层反序打印节点的功能。
56 6
|
3月前
|
搜索推荐 索引 Python
【Leetcode刷题Python】牛客. 数组中未出现的最小正整数
本文介绍了牛客网题目"数组中未出现的最小正整数"的解法,提供了一种满足O(n)时间复杂度和O(1)空间复杂度要求的原地排序算法,并给出了Python实现代码。
113 2
|
19天前
|
机器学习/深度学习 人工智能 自然语言处理
280页PDF,全方位评估OpenAI o1,Leetcode刷题准确率竟这么高
【10月更文挑战第24天】近年来,OpenAI的o1模型在大型语言模型(LLMs)中脱颖而出,展现出卓越的推理能力和知识整合能力。基于Transformer架构,o1模型采用了链式思维和强化学习等先进技术,显著提升了其在编程竞赛、医学影像报告生成、数学问题解决、自然语言推理和芯片设计等领域的表现。本文将全面评估o1模型的性能及其对AI研究和应用的潜在影响。
16 1
|
2月前
|
数据采集 负载均衡 安全
LeetCode刷题 多线程编程九则 | 1188. 设计有限阻塞队列 1242. 多线程网页爬虫 1279. 红绿灯路口
本文提供了多个多线程编程问题的解决方案,包括设计有限阻塞队列、多线程网页爬虫、红绿灯路口等,每个问题都给出了至少一种实现方法,涵盖了互斥锁、条件变量、信号量等线程同步机制的使用。
LeetCode刷题 多线程编程九则 | 1188. 设计有限阻塞队列 1242. 多线程网页爬虫 1279. 红绿灯路口