首页 > 其他 > 详细

[LeetCode]Longest Substring Without Repeating Characters

时间:2015-03-31 12:20:42      阅读:183      评论:0      收藏:0      [点我收藏+]

题意:给定一个字符串,查找最长的子串的长度(没有重复字符)。

原题来自:https://leetcode.com/problems/longest-substring-without-repeating-characters/

分析:

我自己的思路,和曾经做的求最长公共子串长度一样,不过那个是用二维数组,这个一维就ok了,其实就是一个hashtable。

 

 1 class Solution {
 2 public:
 3     int lengthOfLongestSubstring(string s) {
 4         int locs[256];//保存字符上一次出现的位置,由于有分字母,所以弄的这长度
 5         memset(locs, -1, sizeof(locs));
 6         //idx为当前子串的开始位置-1
 7         int idx = -1, max = 0;
 8         for (int i = 0; i < s.size(); i++)
 9         {
10             //如果当前字符出现过,那么当前子串的起始位置为这个字符上一次出现的位置+1
11             if (locs[s[i]] > idx)idx = locs[s[i]];
12             if (i - idx > max)max = i - idx;
13             locs[s[i]] = i;
14         }
15         return max;
16     }
17 };

 

[LeetCode]Longest Substring Without Repeating Characters

原文:http://www.cnblogs.com/orange1438/p/4380397.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!