LeetCode Exercise 3: Longest Substring Without Repeating Characters
来源:互联网 发布:关于sql查询的实训报告 编辑:程序博客网 时间:2024/05/16 11:30
题名:Longest Substring Without Repeating Characters
(最长的无重复字符子串)
难度:medium
题目描述:
个人体会:
不是很了解为什么这道题目会是medium难度,因为没有时间复杂度的约束,这道题看起来中规中矩。
我直接选择了简单粗暴的做法,变量maxLen存储最长子串长度,循环地以string中每一个字符为开头往后扩展子串(剩余string长度小于或等于maxLen时即可停止循环,因为已经可以确认无法再形成更长的子串了),直到遇到重复字符或者到达最后一个字符,结束扩展,修改maxLen的值。
代码如下:
class Solution {public: int lengthOfLongestSubstring(string s) { int n = s.size(); if(n <= 1){ return n; } int len, maxLen = 1; string sub; bool repeat; for(int k = 0; k < n - maxLen; k++){ //以每个子字符为开头构建子串sub len = 1; sub = s[k]; for(int i = k+1; i < n; i++){ //向后扩展子串 repeat = false; for(int j = 0; j < sub.size(); j++){ //检查是否与子串重复字母 if(s[i] == sub[j]){ repeat = true; break; } } if(!repeat){ //无重复,扩展子串sub sub += s[i]; len++; } if(repeat || i == n-1){ //出现重复字母或者已到达最后一个字母,停止往后扩展新子串 if(len > maxLen){ maxLen = len; } break; } } } return maxLen; }};
阅读全文
0 0
- LeetCode Exercise 3: Longest Substring Without Repeating Characters
- LeetCode 3 - Longest Substring Without Repeating Characters
- LeetCode 3: Longest Substring Without Repeating Characters
- leetcode-3:Longest Substring Without Repeating Characters
- LeetCode(3) Longest Substring Without Repeating Characters
- leetcode 3LONGEST SUBSTRING WITHOUT REPEATING CHARACTERS
- Leetcode【3】:Longest Substring Without Repeating Characters
- [leetcode 3] Longest Substring Without Repeating Characters
- [Leetcode] 3 - Longest Substring Without Repeating Characters
- LeetCode 3:《Longest Substring Without Repeating Characters》
- [leetcode 3] Longest Substring Without Repeating Characters
- [leetcode] 3 Longest Substring Without Repeating Characters
- [Leetcode]3Longest Substring Without Repeating Characters
- leetcode 3 Longest Substring Without Repeating Characters
- LeetCode #3 Longest Substring Without Repeating Characters
- leetcode-3 Longest Substring Without Repeating Characters
- LeetCode 3 Longest Substring Without Repeating Characters
- leetcode 3: Longest Substring Without Repeating Characters
- 洛谷题目按难度点评---普及
- Q05现金支付
- VMware Host Only方式联网配置注意
- Q06考拉兹猜想
- ArcGIS 10.0紧凑型切片读写方法
- LeetCode Exercise 3: Longest Substring Without Repeating Characters
- java开发中常用到的快捷键
- office 2016和visio 2016安装说明
- 保卫方案(京东2017笔试题)
- [JSOI2007]重要的城市(x)(洛谷1841)
- 我眼中的MyEclipse、Eclipse、IntelliJ IDEA
- C语言中实现十进制转二进制输出
- 数据结构:用JS实现队列
- JavaScript 事件委托详解