LeeCode--Longest Substring Without Repeating Characters
来源:互联网 发布:linux dd命令 u盘 编辑:程序博客网 时间:2024/05/16 18:16
对于这个题目,我想到了和two sum一样用map来做,可是做出来超过了时间限制,下面把代码贴上来:
class Solution {public:int lengthOfLongestSubstring(string s) { map<char,int>res; int i=0,max=0,n=0; char *p,*q,*pb; pb= p=q=&s[0]; while(p<(pb+s.size())&&q<(pb+s.size())){ if (!res.count(*q)) { res.insert(pair<char,int>(*q,i++)); q++; n= q-p; } else{ p++; if(max>(pb+s.size()-p)) { return max; } q=p; res.clear(); i=0; } if (max<n) max =n; } return max;}};然后想到直接用哈希表来做,以字符为键,以字符所在字符串的位置为值:
public:int lengthOfLongestSubstring(string s) { int pos[512]; int max=0,min=0; for (int i =0;i<512;i++) { pos[i]= -1; } for (int i = 0;i<s.size();i++) { if (pos[s[i]] == -1) { pos[s[i]] = i; } else{ if (i-min>max) { max = i-min; } for (int j =0;j<512;j++) { if (pos[j]!=-1&&pos[j]<pos[s[i]]) { pos[j] = -1; } } min = pos[s[i]]+1; pos[s[i]] = i; } } if (s.size()-min>max) { max = s.size()-min; } return max;}};重点是下面代码的理解:如果从min开始一直都是没有重复的字符,那么就不会进入else语句
if (s.size()-min>max) { max = s.size()-min; }
0 0
- LeeCode--Longest Substring Without Repeating Characters
- LeeCode Longest Substring Without Repeating Characters
- Leecode:Longest Substring Without Repeating Characters
- leecode algo3: Longest Substring Without Repeating Characters (Java)
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- iOS异常处理
- [程序员面试题精选100题]50.树的子结构
- hive 创建分区
- 【史上最简单】android生命周期之home键、返回键、finish()
- android framework层
- LeeCode--Longest Substring Without Repeating Characters
- php 对http内容的解析 $_POST php://input $HTTP_RAW_POST_DATA
- jsp 导出内容到 txt 中。
- 正则表达式语法检测器
- 质数运算
- 修改Tabbar被点击后的文字颜色
- Sublime Text 3 入门
- 关于Spring和公司框架的加载-转自别人写的技术分享,拿来保存学习
- UITableViewCell中的cell addSubView和cell.contentView addSubview