最长无重复字符的子串-LintCode
来源:互联网 发布:80端口入侵教程 编辑:程序博客网 时间:2024/05/17 13:40
给定一个字符串,请找出其中无重复字符的最长子字符串。
样例:
例如,在”abcabcbb”中,其无重复字符的最长子字符串是”abc”,其长度为 3。
对于,”bbbbb”,其无重复字符的最长子字符串为”b”,长度为1。
挑战 :
O(n) 时间
思路:
遍历字符串,对于每个字符计算长度和起始位置,若在已遍历的字符串中不存在,则起始位置不变,直接计算长度;若在已遍历的字符串中存在,更新起始位置,计算长度,最终取最大长度。
#ifndef C384_H#define C384_H#include<iostream>#include<vector>#include<map>using namespace std;class Solution {public: /* * @param s: a string * @return: an integer */ int lengthOfLongestSubstring(string &s) { // write your code here if (s.empty()) return 0; int res = 0; int start = 0; map<char, int> m; for (int i = 0; i < s.size();++i) { if (m.find(s[i]) == m.end()) { m[s[i]] = i; } else { start = maxVal(m.find(s[i])->second+1,start); m.find(s[i])->second = i; } res = maxVal(res, i - start + 1); } return res; } int maxVal(int a, int b) { return a > b ? a : b; }};#endif
阅读全文
0 0
- LintCode-最长无重复字符的子串
- LintCode-最长无重复字符的子串
- LintCode:最长无重复字符的子串
- 最长无重复字符的子串 lintcode
- lintcode,最长无重复字符的子串
- lintcode(384)最长无重复字符的子串
- lintcode--最长无重复字符的子串
- [LintCode]384.最长无重复字符的子串
- LintCode:M-最长无重复字符的子串
- [LintCode 384] 最长无重复字符的子串(Python)
- lintcode最长无重复字符的子串
- LintCode 最长无重复字符的子串
- 最长无重复字符的子串-LintCode
- 最长无重复字符的子串
- 最长无重复字符的子串
- 最长无重复字符的子串
- 最长无重复字符的子串
- 最长无重复字符的子串
- 无法升级数据库 'SchoolPlatForm1',因为它是只读的,或者具有只读文件。请将数据库或文件设为可写,然后重新运行恢复操作。 (Microsoft SQL Server,错误: 3415)
- POJ3264-Balanced Lineup
- java内存机制中的堆栈常量池简介
- C/C++面试题(三)
- Dol嵌入式软件之安装
- 最长无重复字符的子串-LintCode
- C/C++面试题(四)
- java设计模式-工厂模式
- MTK LCM显示驱动源码分析(一)
- 【noip2009】靶形数独(搜索+二进制优化)
- 浓墨重彩之OpenStack-开篇声明。
- 虚拟机下创建共享文件夹时找不到设置的文件夹
- bzoj1196 [HNOI2006]公路修建问题 二分
- 深度学习笔记(1)------linux Ubuntu 14.04+Anaconda2+opencv 3.2.0+caffe-master配置