LEETCODE: Longest Substring Without Repeating characters

来源:互联网 发布:淘宝怎么搜爱弹幕账号 编辑:程序博客网 时间:2024/06/06 17:43

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 "bbbb" the longest substring is "b", with the length of 1.

这是一个字符串的题目,可能的结果当然是任意的子串。最简单的办法就是从每一个位置出发,找到该位置可能的最大长度的子串。由于子串里是没有重复的,那么,所有相同的字符就把当前的字符串分成了N个片段。所以我们要考虑的是在遇到第二个相同的字符串的时候需要一些什么操作。这样的话,我们就必须把各个字符出现的位置或者是否出现过记录下来。

      int start = 0, newEnd = 0;      int n = s.size();      int maxLen = 0;      int exist[256];      for(int kk = 0; kk < 256; kk ++)         exist[kk] = -1;
我才用的方法是记住每个字符最后出现的位置,因此用的是一个包含256个元素的int数组。用start来记录子串的初始位置,用newEnd记录可能的结束位置。

class Solution {public:   static int lengthOfLongestSubstring(string s) {      if(s.size() == 0) return 0;      int start = 0, newEnd = 0;      int n = s.size();      int maxLen = 0;      int exist[256];      for(int kk = 0; kk < 256; kk ++)         exist[kk] = -1;      for(;newEnd < n; newEnd ++)      {         // If current character (s[newEnd]) occurs more than one time.         // Find the new max length and set the new start point.         // The new start point is just after the prior position of character s[newEnd].         if(exist[s[newEnd]] >= start)         {            maxLen = max(maxLen, newEnd - start);            start = exist[s[newEnd]] + 1;         }         // Always record the current character the current position.         exist[s[newEnd]] = newEnd;      }      maxLen = max(maxLen, newEnd - start);      return maxLen;   }};

这个算法的大体思路是,遍历这个string,同时记录下来当前子串的起始位置,如果新遇到的字符没有出现过,就记录下来。如果出现过,那么看看子串的长度是否需要跟新,同时把子串新的起始位置改成当前这个字符上次出现的那个位置的后一个位置上。

这是我的方法,当然,我也看到有别人用bool数组来记录的,但是那样需要查找才能确定新的起始位置。当然,bool需要的空间比int要小。


0 0
原创粉丝点击