LeetCode之Longest Substring Without Repeating Characters
来源:互联网 发布:mac 能用的刻录机 编辑:程序博客网 时间:2024/05/28 14:56
一、题目
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.
二、考虑过程
比如输入jbpnbwwd,首先从头开始统计子字符串,当出现重复字符时,开始下一个子字符串的统计,但是要注意下一个子字符串的统计位置应该是从第一次出现相同字符的下一位开始。
三、代码
class Solution {public: int lengthOfLongestSubstring(string s) { string ans[2] = {"",""}; int len[2] = {0,0}; for(unsigned int i=0; i<s.size(); i++){ string::size_type pos = ans[1].find(s[i]); if(pos==string::npos){ ans[1] += s[i]; len[1]++; }else{ if(len[0]<len[1]){ len[0] = len[1]; ans[0] = ans[1]; } len[1] = 0; ans[1] = ""; string::size_type rpos = s.rfind(s[i],i-1); i = i - (i-rpos-1); //这里注意为什么从重复字符的第一个的下一位开始:如果再将位置往前移的话肯定包括了当前的重复字符,只有从下一位才不会同时包含两个相同字符。 i--; } } if(len[0]<len[1]){ return len[1]; }else{ return len[0]; } }};
四、另一种
另一种方式:考虑到最大子串要么是整个字符串;要么就是两个相同字符间距离。可以用map存储第一个字符,当出现相同字符时加以判断。
class Solution {public: int lengthOfLongestSubstring(string s) { int maxl=0,tem=0; unordered_map<char,int> con; for(int i=0; i<s.size(); i++){ if(con.count(s[i])){ tem = max(tem,con[s[i]]+1); //一般情况下,应该时map记录的两个字符间距,但是,如果出现两个相同字符串交叉问题,就要修改一下。 } con[s[i]] = i; maxl = max(maxl,i-tem+1); } return maxl; }};
0 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之 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之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
- Odoo ORM API(七)- Porting from the old API to the new API
- WebPack模块化开发
- Java实现服务器与客户端网络通信
- leveldb源码分析--SSTable之Compaction 详解
- hdu 4619 Warm up 2【二分匹配】
- LeetCode之Longest Substring Without Repeating Characters
- java -- 异常处理(2)
- 移动端网页布局中需要注意事项以及解决方法总结
- 开源项目收集
- Java - 1Web应用服务器1______软件开发-JAVA
- 二级指针删除链表
- 学习Hadoop第十四课(自定义分区Partitioner)
- 移动APP界面的加载动画与进度条
- idea配置 git 和maven环境