L_J_SHOU

LeetCode----Longest Substring Without Repeating Characters

Longest Substring Without Repeating Characters

 
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.

时间复杂度 O(n) ,空间复杂度 O(1)


int lengthOfLongestSubstring(string str) {
  int len = str.size();
  if(len < 2) return len;

  /* hash table */
  vector<int> hash(26, -1);
  int s(0), t(0), longest(0);
  hash[str[0] - 'a'] = 0;

  for(t=1; t<len; ++t)
  {
    if(hash[str[t]-'a'] == -1 || hash[str[t]-'a'] < s)
	{
	  hash[str[t]-'a'] = t;
	}
	else /* 重复 */
	{
	  longest = max(longest, t-s); 
	  s = hash[str[t]-'a'] + 1;
	  hash[str[t] - 'a'] = t;
	}
  }
  longest = max(longest, t-s);

  return longest;
}


posted on 2014-02-16 13:14  L_J_SHOU  阅读(130)  评论(0)    收藏  举报