zoukankan      html  css  js  c++  java
  • 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上看到的另一种思路是这样子的:

  • 相关阅读:
    .Net时间计算函数,统计某一天是一年的第几周,这一周从哪天开始到哪天结束
    1分钟搞定超慢SQL
    网站
    舞台
    相见欢
    一套完整系统对人生的意义
    2015/08/15心情
    Linux下压缩某个文件夹(文件夹打包)
    init进程 && 解析Android启动脚本init.rc && 修改它使不启动android && init.rc中启动一个sh文件
    andriod系统裁剪心得
  • 原文地址:https://www.cnblogs.com/tracy520/p/8320928.html
Copyright © 2011-2022 走看看