Leetcode Problem 3: Longest non-repeated substring(LNRS).

Description:

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.

Solution

先谈谈耗时最长的算法,时间复杂度O(n^3);第一步,先从从左向右枚举出一个字符串所有的子字符串,需要耗时O(n^2);第二步,针对每一个子串,判断该字符串是否含有重复字符,需要耗时O(n);

这里我的改进点在第二步,优化判断该字符串是否含有重复字符,使它达到O(1),也就是在常数时间内查找出结果。我们知道ASCII编码一共含有255个字符,可以用hash的思想,使用一个数组,将字符一一映射到对应的ASCII。这个数组长度为256,这样便可以达到优化的效果。

Code

/**
 * Leetcode Problem 3: Longest Substring Without Repeating Characters
 * Hash ( character -> ASCII)
 *
 * hellfire (asyncloading#163.com)
 * Feb 16th, 2016
 */
#include<iostream>

using namespace std;

class Solution {
  public:
    int lengthOfLongestSubstring(string s) {
      int max_len = 0;
      int visited[256];     
      int str_size = s.length();

      if (str_size == 1)
      {
        return 1;
      }

      for (int i = 0; i < str_size; i ++)
      {
        memset(visited, 0, sizeof(visited));      /* Clear memory visited array. */
        visited[s[i]] = 1;
        bool has_repeated = false;
        for (int j = i + 1; j < str_size; j ++)
        {
          if (visited[s[j]] == 0)
          {
            visited[s[j]] = 1;
          }
          else
          {
            has_repeated = true;
            if (j - i > max_len)
            {
              max_len = j - i;
            }
            break;
          }
        }
        if (!has_repeated)
        {
          if (max_len < str_size - i)
          {
            max_len = str_size - i;
          }
        }            
      }
      return max_len;
    }
};

int main(int argc, char **argv)
{
  Solution s;
  string str = "abcabcabcbacde";
  int max_len = s.lengthOfLongestSubstring(str);
  cout << max_len << endl;  
}

Github源代码:https://github.com/oj-problem/leetcode/blob/master/solution3.cpp

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值