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 };
  • 相关阅读:
    数据库的范式
    数据库的事务
    cookie和session以及区别
    Java交换排序:冒泡排序和快速排序
    Java面向对象中:方法重载和方法重写以及区别、 this关键字和super关键字以及区别
    电子设备产品可靠性测试
    软件测试思考笔记(The beauty of software testing)
    常见软件系统架构解决方案
    常见计算机系统架构
    性能测试
  • 原文地址:https://www.cnblogs.com/easonliu/p/3634899.html
Copyright © 2011-2022 走看看