LeetCode Algorithms 3. Longest Substring Without Repeating Characters
来源:互联网 发布:js页面中return fslse 编辑:程序博客网 时间:2024/05/16 14:51
题目难度: Medium
原题描述:
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.
题目大意:
给你一个字符串,找出其不含相同字符的最长子串。
解题思路:
用指针i从前往后扫描字符串,用一个index数组记录每一个字符最后一次出现在原字符串中的下标,没有出现过的为-1,index数组的下标为每一个字符的ASCII码。用max记录当前不含相同字符的最长子串的长度,指针j记录当前子串的起始位置。当第一次遇到某个字符时,将这个字符对应的index数组的值改为字符串的当前下标;当再次遇到某个字符时,i-j即为当前最长子串的长度,用此值和max比较并更新max,此外还要将j值更新为重复字符在第一次出现时的后一位置,并将此位置之前的字符的index数组的值置为-1。最后将重复字符对应的index数组的值更新。
时间复杂度分析:
由于指针i和j都是扫描字符串一遍,因此总的时间复杂度为O(n),n为字符串的长度。
以下是代码:
int getMax(int a , int b){ return a>b ? a : b;}int lengthOfLongestSubstring(char* s){ int i,j,k,m; int index[200]; int ans = 0; memset(index,-1,sizeof(index)); for(i=0,j=0 ; s[i]!='\0' ; ++i) { if( index[s[i]]==-1 ) { index[s[i]] = i; } else { ans = getMax(ans,(i-j)); m = j; j = index[s[i]] + 1; for(k=m ; k<j ; ++k) index[s[k]] = -1; index[s[i]] = i; } } ans = getMax(ans,(i-j)); return ans;}
0 0
- LeetCode Algorithms 3. Longest Substring Without Repeating Characters 题解
- LeetCode Algorithms 3. Longest Substring Without Repeating Characters
- leetcode Algorithms 3. Longest Substring Without Repeating Characters
- [LeetCode] Algorithms-3.Longest Substring Without Repeating Characters
- [LeetCode-Algorithms-3] "Longest Substring Without Repeating Characters" (2017.9.8)
- [LeetCode]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] 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】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 - 3.Longest Substring Without Repeating Characters
- 去交错Deinterlace算法介绍
- erlang 开启两万个线程(练习)
- cocoapods 执行 pod search 命令失败解决办法
- JAVA学习笔记---WebService调用别人的接口
- shell脚本中一些特殊符号
- LeetCode Algorithms 3. Longest Substring Without Repeating Characters
- Json解析时,一系列opt***方法
- ng-table使用笔记-遇到的问题及解决方案
- iOS项目引用外界字体库
- linux如何配置php环境
- 1625 夹克爷发红包(二进制枚举运用)
- 第九周:136. Single Number
- 最大的数---贪心算法
- Unicode、UTF-8 和 ISO8859-1到底有什么区别