leetcode-3. Longest Substring Without Repeating Characters
2016-05-03 23:50
204 查看
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.
Subscribe to see which companies asked this question
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.
Subscribe to see which companies asked this question
class Solution { public: int lengthOfLongestSubstring(string s) { //遍历,hash表存,key为字符,value为对应下标, //两个指针一左一右,右的往后遍历并让字符入hash,当重复时左指针移到对应下标的下一个 if(s.size() == 0) { return 0; } int left = 0; int right = 0; int result = 0; map<char,int> myMap; for(int i=0;i<s.size();i++) { right = i; //找到了 if(myMap.find(s[i]) != myMap.end()) { //如果在left前面的话还要更新index if(myMap[s[i]] < left) { myMap[s[i]] = i; continue; } //这时要先保存目前为止的最长子串,不包括最后一个字符,不加1 if(result < right - left) { result = right - left; } left = myMap[s[i]] + 1; //更新相同字符index myMap[s[i]] = i; } else { myMap.insert(make_pair(s[i],i)); } } return max(result,right - left+1); } };
相关文章推荐
- HDU 2044 一只小蜜蜂...(递推+打表)
- printf()函数的输出格式
- Apache Tomcat服务器的公网访问问题解决方案
- [Android]Android5.0如何去除标题栏
- 使用SSM(Simple-Spring-Memcached)的一些心得
- Android代码中加解密方式
- 在CSDN上发布视频blog
- python之迭代
- Linux基本命令练习(1)
- 实验7 201306114104彭得源
- APP接入QQ登陆功能报错“该应用非官方正版应用,请到......100044”的几种错误
- Android native和h5混合开发几种常见的hybrid通信方式
- ProGuard详解
- JAVA自学之路 ——尚学堂科技马士兵
- Generative Modeling of Convolutional Neural Networks,生成式CNNs
- python中list操作详解
- Xcode删除所有断点
- VMware Workstation cannot connect to the virtual machine
- Android中Build Target,minSdkVersitarget,targetSdkversion概念
- Velocity模板引擎下 velocity.properties转义(转码)配置