【Leetcode】Longest Substring Without Repeating Characters
来源:互联网 发布:手机淘宝如何申请介入 编辑:程序博客网 时间:2024/06/03 21:52
问题:
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
代码:
//// lssworc.cpp// Test//// Created by mac on 5/19/14.// Copyright (c) 2014 mac. All rights reserved.//#include "lssworc.h"#include <iostream>#include <stdlib.h>#include <string.h>using namespace std;class Solution {public: int lengthOfLongestSubstring(string s) { int cache[256]; memset(cache , 0 , sizeof(cache)); int maxR = 0; int temp = 0; int start = 0; for (int i = 0 ,start = 0; i < s.length() && start < s.length(); i++) { int size = s[i]; temp ++; if(++cache[size] > 1) { maxR = max(maxR , temp-1); do { int haha = s[start]; cache[haha] --; temp --; if(s[start] == s[i]) { cout<<s[start]<<endl; start ++; cout<<temp<<endl; break; } start ++; }while(1); } } maxR = max(maxR , temp-1); return maxR; }};int main(){ Solution s; cout<<s.lengthOfLongestSubstring(string("wlrbbmqbhcdarzowkkyhiddqscdxrjmowfrxsjybldbefsarcbynecdyggxxpklorellnmpapqfwkhopkmco"))<<endl;}
分析:
原理很简单:
1. 因为一个字符只有一个字节,所以最大值是 255,基于这一点,设置一个 256 的cache,来统计所有的字符出现的次数,如果次数大于1,则出现的是第二次了。
2. 基于第一点,从新的字符串开始找到重复的那个字符,并缩减到最大字串,从重复的下一个开始重新统计。
总结:
这个还是比较有成就感,自己想出来的解法。只能说明字符串功底还行。再接再厉。
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 23: Longest Substring Without Repeating Characters
- [LeetCode] Longest Substring Without Repeating Characters
- LeetCode 3 - 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 3: Longest Substring Without Repeating Characters
- leetcode-3:Longest Substring Without Repeating Characters
- leetcode之Longest Substring Without Repeating Characters
- Factory 'javax.faces.render.RenderKitFactory' was not configured properly.
- tornado模板机制_在模板里面编程
- Service与Android系统设计(6)--- Native Service
- 21天战拖记——Day16:系统化,接着填“衣柜整理法”的坑(2014-05-19)
- 对你同样重要的非技术贴,8个方法让你成为下一个晋升对象
- 【Leetcode】Longest Substring Without Repeating Characters
- 3Sum Closest
- Winsocket 一:单线程阻塞server&client程序(tcp)
- Excel VBA编程基础
- 3种浏览器性能测试
- 欢迎来到魔法的未来~
- hdu2571命运
- adb常用命令教程
- 感受