zoukankan      html  css  js  c++  java
  • [Leetcode] 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.

    动态规划,注意空字符串。

     1 class Solution {
     2 public:
     3     int lengthOfLongestSubstring(string s) {
     4         int n  = s.length();
     5         if (n == 0) {
     6             return 0;
     7         }
     8         int *a = new int[n];
     9         int max = 1, tmp;
    10         a[0] = 1;
    11         bool flag;
    12         for (int i = 1; i < n; ++i) {
    13             flag = true;
    14             tmp = 1;
    15             for (int j = 1; j <= a[i-1]; ++j) {
    16                 if (s[i-j] == s[i]) {
    17                     tmp = j;
    18                     flag = false;
    19                     break;
    20                 }
    21             }
    22             a[i] = flag ? a[i-1] + 1 : tmp;
    23             max = a[i] > max ? a[i] : max;
    24         }
    25         return max;
    26     }
    27 };

     滑动窗口!

     1 class Solution {
     2 public:
     3     int lengthOfLongestSubstring(string s) {
     4         int len = 0;
     5         bool flag[256] = {false};
     6         int start = 0;
     7         for (int i = 0; i < s.length(); ++i) {
     8             if (flag[s[i]]) {
     9                 while (s[start] != s[i]) {
    10                     flag[s[start]] = false;
    11                     ++start;
    12                 }
    13                 ++start;
    14             }
    15             flag[s[i]] = true;
    16             len = max(len, i - start + 1);
    17         }
    18         return len;
    19     }
    20 };

     还可以再优化一点!

     1 class Solution {
     2 public:
     3     int lengthOfLongestSubstring(string s) {
     4         int len = 0;
     5         int pos[256];
     6         for (int i = 0; i < 256; ++i) pos[i] = -1;
     7         int start = 0;
     8         for (int i = 0; i < s.length(); ++i) {
     9             if (pos[s[i]] >= start) {
    10                 start = pos[s[i]] + 1;
    11             }
    12             pos[s[i]] = i;
    13             len = max(len, i - start + 1);
    14         }
    15         return len;
    16     }
    17 };
  • 相关阅读:
    2019第二周作业
    求最大值及其下标
    查找整数
    2018秋季学习总结
    抓老鼠 亏了还是赚了
    币值转换
    打印沙漏
    从文本中找出url,并附上链接。
    手机端点击输入框页面会放大
    <dl>、<dt>和<dd>标记的用法
  • 原文地址:https://www.cnblogs.com/easonliu/p/3634899.html
Copyright © 2011-2022 走看看