LeetCode 第 3 题(Longest Substring Without Repeating Characters)

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.

求一个字符串的最长无反复子串。也是个比較简单的题目。

涉及到的知识点主要是字符串操作和怎样确定字符是否反复。遍历一个字符串能够用 iterator。推断一个字符是否出现过能够用集合(set)类型。

因此, 我在程序中设立了一个 std::set 型变量 dict。

推断一个字符是否在 dict 中存在,用的是 count() 方法,返回 0 表示不存在这个字符。加入一个字符用的是 insert 方法,删除一个字符是 erase 方法。

另外一个要点是怎样遍历这个字符串。我的程序中设计了头尾两个指针。先用头指针遍历字符串。中间碰到有反复字符了就移动尾指针。直到头尾指针之间没有反复字符为止。这样我的程序仅仅需实时监控头尾指针之间的最大距离即可了。

以下是代码:

int lengthOfLongestSubstring(string s)
{
string::const_iterator head = s.cbegin();
string::const_iterator tail = s.cbegin();
std::set<char> dict;
int count, maxCount = 0;
while( head != s.cend() )
{
if( dict.count(*head) == 0)
{
dict.insert(*head);
count = dict.size();
maxCount = (count > maxCount) ? count : maxCount;
}
else
{
while( *tail != *head )
{
dict.erase(*tail);
++tail;
}
++tail;
}
++head;
}
return maxCount;
}

这个代码尽管计算结果是正确的。可是执行速度略慢。要想提高执行速度,还是要在判别一个字符是否反复的算法上下功夫。由于常见的英文字符就那么几个,所以能够直接用查表法来处理。以下是改进后的代码。

执行速度快了不少。

int lengthOfLongestSubstring(string s)
{
string::const_iterator head = s.cbegin();
string::const_iterator tail = s.cbegin();
char dict[128];
memset(dict, 0, 128);
int count = 0, maxCount = 0;
while( head != s.cend() )
{
if( dict[*head] == 0)
{
dict[*head] = 1;
++ count;
maxCount = (count > maxCount) ? count : maxCount;
}
else
{
while( *tail != *head )
{
dict[*tail] = 0;
-- count;
++tail;
}
++tail;
}
++head;
}
return maxCount;
}

最新文章

  1. openresty 前端开发入门五之Mysql篇
  2. ember.js里的实用方法
  3. Leetcode: Matchsticks to Square &amp;&amp; Grammar: reverse an primative array
  4. archlinux 安装过程记录
  5. 用 perl 统计 fasta 文件序列的总长
  6. 15个易遗忘的Java问题
  7. FoxOne---一个快速高效的BS框架--WEB控件属性编辑器
  8. Windows 2008 R2下 如何简单使用IIS来配置PHP网站
  9. MyBatis学习总结——实现关联表查询(转)
  10. (生活)Photoshop入门(不定时更新)
  11. python进程间通信
  12. markdown 基本语法(转载)
  13. js layer.js
  14. XCode 无法识别设备
  15. Python如何输出带颜色的文字方法
  16. 3DMax——室内设计:墙体+吊顶
  17. windows10删除开始菜单中的xbox、人脉、邮件等应用
  18. 文件打包代码更新 使用json记录打包文件信息
  19. 如何把GitHub中的开源项目导入到Eclipse
  20. 《Java 程序设计》课堂实践三

热门文章

  1. iOS开发中六种手势识别
  2. 【Luogu】P3704数字表格(莫比乌斯反演+大胆暴力)
  3. kb-01-a&lt;简单搜索--dfs八皇后问题变种&gt;
  4. HDU——1020Encoding(水题,string过)
  5. 刷题总结——字符串(ssoj)
  6. bzoj 2300 [HAOI2011]防线修建 set动态维护凸包
  7. 转 Python爬虫入门七之正则表达式
  8. hdu 4183(网络流)
  9. 本地hosts文件
  10. ML | PCA