3. Longest Substring Without Repeating Characters

题面

Given a string, find the length of the longest substring without repeating characters.

给定字符串,找到最长无重复字串的长度

样例

Example 1:

Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.

Example 2:

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: "pwwkew"
Output: 3
Explanation: 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.

思路

开始的思路是,蠢笨的滑动窗口

1.遍历字符串

2.以每个字符串为基准,向后搜索,暂存不重复的字符,遇到重复字符,结束内循环,统计不重复字符个数,更新结果。

时间复杂度:O(n3)

空间复杂度:> O(n)

 class Solution {
public:
int lengthOfLongestSubstring(string s) {
int res = ;
int len = s.length();
if(len <= )
return len;
for(int i=; i<len; i++)
{
string tmpStr = "";
int k = i;
while(!find(tmpStr, s[k]) && k < len)
{
tmpStr += s[k];
k++;
}
if(tmpStr.length() > res)
res = tmpStr.length();
}
return res;
}
//搜索元素是否存在(已经记录过)
bool find(string str, char c)
{
for(int j=; j<str.length(); j++)
if(str[j] == c)
return true;
return false;
}
};

优化?改进搜索复杂度

使用string find(char c)函数来替换我自己实现的find()函数,果然快了好多。

时间复杂度:大于O(n2) 小于 O(n3)

 class Solution {
public:
int lengthOfLongestSubstring(string s) {
int res = ;
int len = s.length();
if(len <= )
return len;
for(int i=; i<len; i++)
{
string tmpStr = "";
int k = i;
         //使用string find函数替换我的find函数
while(tmpStr.find(s[k]) == tmpStr.npos && k < len)
{
tmpStr += s[k];
k++;
}
if(tmpStr.length() > res)
res = tmpStr.length();
}
return res;
}
};

当我使用unordered_map<char, char>来存储元素后,发现用时和空间没有继续减小,反而增大了许多,几乎与最开始采用的方法一致了。比较奇怪!

那么有没有办法消除一层循环呢?

待续......

最新文章

  1. WinformWPF 多线程访问控件【转】
  2. ACM: FZU 2112 Tickets - 欧拉回路 - 并查集
  3. 关于string,我今天科普的
  4. 【Selenium】2.安装Selenium IDE和 FireBug
  5. SQL 递归 可以用于权限查找。迭代自身没有用递归函数。
  6. 在http编程的门口----飞牛网自动下单,查单
  7. JavaScript运行原理解析
  8. wpf软件某些分辨率下文字模糊解决方法
  9. Python开发工具PyCharm个性化设置
  10. sqlserver配置允许快照隔离
  11. internal table operation
  12. EntityFramework安装和EF升级方法
  13. win7+php5.3.10下安装memcache (转)
  14. 洛谷P1038神经网络
  15. poj-2253-poj-1797_最短路练习
  16. switch case :在JDK 7中,又加入了对String类型的支持,从此不用再写If-Else来判断字符串了
  17. CentOS7.2编译配置LNMP环境(MySQL5.7.20,PHP7.0.24)
  18. 【洛谷】P1541 乌龟棋(四维背包dp)
  19. python-网易云简单爬虫
  20. AOJ.综合训练.2016-12-1

热门文章

  1. 解决微信小程序textarea层级太高遮挡其他组件的问题
  2. Python 爬虫从入门到进阶之路
  3. centos7.5安装图形界面
  4. CSS基础(html+css基础)
  5. SQL Server数据同步交换
  6. Egret入门学习日记 --- 第八篇(书中 2.0~2.6节 内容)
  7. mysql数据恢复,binlog详解
  8. linux下使用Oracle常用命令
  9. java日志框架系列(8):logback框架PatternLayout详解
  10. java日志框架系列(4):logback框架xml配置文件语法