• leetcode 3 Longest Substring Without Repeating Characters


    题目:

    Given a string, find the length of the longest substring without repeating characters.

    Examples:

    Given "abcabcbb", the answer is "abc", which the length is 3.

    Given "bbbbb", the answer is "b", with the length of 1.

    Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke"is a subsequence and not a substring.

    思路:

    题意就是给找到一个最长的没有重复字符的子串。我定义了一个bool数组用来表示对应的字符是否出现过。指针从左往右移动,如果遇到出现过的字符,就停止,跟当前max_length比较。清掉前面的字符串直至重复的字符,同时将bool数组更新。

    代码:

     1 class Solution
     2 {
     3 public:
     4     int lengthOfLongestSubstring(string s)
     5     {
     6         int sz = s.size();
     7         bool occ[128] = {0};
     8         int result = 0;
     9         int length = 0;
    10         for(int i = 0; i < sz; i++)
    11         {
    12             int temp = (int)s[i];
    13             if(occ[temp])
    14             {
    15                 if(length > result)
    16                 {
    17                     result = length;
    18                 }
    19                 for(int j = i - length;j < i && (int)s[j] != temp;j++)
    20                 {
    21                     occ[(int)s[j]] = 0;
    22                     length--;
    23                 }
    24             }
    25             else
    26             {
    27                 occ[temp] = 1;
    28                 length++;
    29             }
    30         }
    31         if(length > result)
    32             result = length;
    33         return result;
    34     }
    35 };

    参照leetcode上面的代码发现可以通过关闭输出流同步来减少运行时间:

    1 static int close(){
    2     ios::sync_with_stdio(false);
    3     cin.tie(0);
    4     return 0;
    5 }

    leetcode上看到的另一种思路是这样子的:

  • 相关阅读:
    转载:渗透利器-余弦
    搜索引擎?
    Gartner:用自适应安全架构来应对高级定向攻击
    内网渗透测试思路-FREEBUF
    渗透测试常规思路分析-FREEBUF
    SQLMAP使用笔记
    如何打造一款优秀的产品管理系统?
    阿里的钉钉能干掉腾讯的微信么?
    下一个亿万市场:企业级SaaS服务谁能独领风骚
    如何注册iClap账号?
  • 原文地址:https://www.cnblogs.com/tracy520/p/8320928.html
Copyright © 2020-2023  润新知