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.size();
     5         int ans = 0;
     6         bool exist[256];
     7         memset(exist, false, sizeof(exist));
     8         int start = 0, end = 0;
     9         while (end < n && start + ans < n) {
    10             if (exist[s[end]]) {
    11                 exist[s[start++]] = false;
    12             } else {
    13                 exist[s[end++]] = true;
    14             }
    15             ans = max(ans, end - start);
    16         }
    17         return ans;
    18     }
    19 };

    方法二:

    用一个index数组记录每个字符上一次出现的位置,同样是设置窗口并移动,但是遇到重复字符字符时就可以知道重复字符上次出现的位置,将开始位置移到该位置之后。

     1 class Solution {
     2 public:
     3     int lengthOfLongestSubstring(string s) {
     4         int n = s.size();
     5         int ans = 0;
     6         int index[256];
     7         memset(index, -1, sizeof(index));
     8         int start = 0, end = 0;
     9         while (end < n && start + ans < n) {
    10             if (index[s[end]] < start) {
    11                 index[s[end]] = end;
    12                 ++end;
    13                 ans = max(ans, end - start);
    14             } else {
    15                 start = index[s[end]] + 1;
    16             }
    17         }
    18         return ans;
    19     }
    20 };
  • 相关阅读:
    IFRAME自适应高度
    项目支出数据产生过程
    hbase体系结构以及说明
    PLSQL 设置
    hadoop编程模型
    捕捉桌面上的窗口信息
    在不修改代码的情况下无限扩展应用项目
    跟我一起玩Win32开发(25):监视剪贴板
    跟我一起玩Win32开发(24):计时器
    跟我一起玩Win32开发(23):渐变颜色填充
  • 原文地址:https://www.cnblogs.com/dengeven/p/4005429.html
Copyright © 2011-2022 走看看