Longest Substring Without Repeating Characters

LeetCode OJ 3: Given a string, find the length of the longest substring without repeating characters.

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", 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:本题的任务是得到没有重复字符的最长子串的长度。我的解法是使用i和j两个指针进行搜索,i代表候选的最长子串的开头,j代表候选的最长子串的结尾。搜索过程中,如果字符j重复出现,则从重复字符第一次出现的位置开始重新搜索,直到遍历所有的可能性。

时间复杂度:O(N²)

int lengthOfLongestSubstring(string s) {
  int maxLen, i, j, k, curLen;
  int char_int_arr[256];  
  maxLen = i = j = 0;
  while(i < s.length() && j < s.length())
  {
    for(j = 0; j < 256; j++)
    char_int_arr[j] = -1;
    for(k = j = i; j < s.length(); j++)
    {
      if(char_int_arr[s[j]] != -1)
      {
        i = char_int_arr[s[j]] + 1;
        break;
      }
      else
        char_int_arr[s[j]] = j;
    }
    curLen = j - k;
    if(maxLen < curLen)
      maxLen = curLen;
  }
  return maxLen;
}

思路2:仔细观察可以发现,解法1在子串搜索的过程中做了很多重复的工作。检索到重复字符后,两个重复字符之间的子串不会存在其他重复字符,所以这一段区间可以不用再次遍历。

时间复杂度:O(N)

int lengthOfLongestSubstring(string s) { 
  int n = s.length(); 
  int i = 0, j = 0; 
  int maxLen = 0; 
  bool exist[256] = { false }; 
  while (j < n) { 
    if (exist[s[j]]) { 
      maxLen = max(maxLen, j-i); 
      while (s[i] != s[j]) { 
      exist[s[i]] = false; 
      i++; 
      } 
    i++; 
    j++; 
    } else { 
      exist[s[j]] = true; 
      j++; 
    }   
  } 
  maxLen = max(maxLen, n-i); 
  return maxLen; 
}

 

posted @ 2016-07-12 19:20  信步闲庭、、  阅读(272)  评论(0编辑  收藏  举报