【leetcode】Longest Substring Without Repeating Characters
来源:互联网 发布:python课程推荐 编辑:程序博客网 时间:2024/05/29 18:10
题目:
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
用DP和Hash的思想做这道题,建立一个大小为26的数组,记录a~z每个字符最新出现的字符串位置。用变量count记录包含当前字符的子串已有的最长长度。遍历字符串的每一个字符,如果某个字符对应hash数组中的值在count范围内,更新count的值。如果某个字符对应hash数组中的值在count范围外,更新hash的值并且count++,还要判断是否要更新最长子串长度max。时间复杂度为O(N),C++ AC代码如下:
int lengthOfLongestSubstring(string s) { int hash[26]; int i; for (i = 0; i < 26; i++){ hash[i] = -1; //所有字母的初始位置都为-1,注意不能为0 } int count = 0,max=0; for (i = 0; i < s .length(); i++){ int temp = s [i] - 'a'; if (hash[temp]<(i - count)){ count++; if (count>max){ max = count; } }else{ count = i - hash[temp]; } hash[temp] = i; } if (count>max){ max = count; } return max;}
1 0
- LeetCode: Longest Substring Without Repeating Characters
- LeetCode Longest Substring Without Repeating Characters
- LeetCode: Longest Substring Without Repeating Characters
- [Leetcode] Longest Substring Without Repeating Characters
- leetcode 23: Longest Substring Without Repeating Characters
- [LeetCode] Longest Substring Without Repeating Characters
- LeetCode 3 - Longest Substring Without Repeating Characters
- [LeetCode]Longest Substring Without Repeating Characters
- leetcode Longest Substring Without Repeating Characters
- 【leetcode】 Longest Substring Without Repeating Characters
- LeetCode-Longest Substring Without Repeating Characters
- [LeetCode] Longest Substring Without Repeating Characters
- [LeetCode] Longest Substring Without Repeating Characters
- [leetcode] Longest Substring Without Repeating Characters
- LeetCode - Longest Substring Without Repeating Characters
- LeetCode 3: Longest Substring Without Repeating Characters
- leetcode-3:Longest Substring Without Repeating Characters
- leetcode之Longest Substring Without Repeating Characters
- CentOS 6.5系统中安装配置MySQL数据库
- MyEclipse破解 注册机“System id无法生成”解决方法
- 定义一个公共方法,打造自己的AJAX框架
- 使用Python绘制图表实例
- CentOS系统安装MySQL workbench图文教程
- 【leetcode】Longest Substring Without Repeating Characters
- hdu4915 判断括号匹配
- 汇编语言03——第一个汇编程序
- uva 10626 - Buying Coke
- Android视图绘制流程完全解析,带你一步步深入了解View(二)
- 生成子集以及置换
- CentOS 6.5系统中如何安装MySQL 5.6.10数据库和修改root密码
- 菜鸟译文(一)——Java中的继承和组合
- HLS入门收集(1)