zoukankan      html  css  js  c++  java
  • LeetCode 3 Longest Substring Without Repeating Characters(最长不重复子序列)

    题目来源:https://leetcode.com/problems/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

    解题思路:

    用一个start来记录目前字符串的开头
    用exist[MAX]来记录目前字符串中出现过的字母
    用pos[MAX]来记录出现过的字符串的字母的位置
     
    然后我们往后走一位,然后和exist来比较看这个字母是否已经出现过了。
     
    1 如果出现过了,那么我们把start移动到之前那个字母出现的位置的后一位,end往后移动一位
    2 如果没有出现过,那么我们就把end往后移动一位
    提交代码:
     1 class Solution {
     2 public:
     3     int lengthOfLongestSubstring(string s) {
     4         // Start typing your C/C++ solution below
     5         // DO NOT write int main() function
     6         int locs[256];//保存字符上一次出现的位置
     7         memset(locs, -1, sizeof(locs));
     8 
     9         int idx = -1, max = 0;//idx为当前子串的开始位置-1
    10         for (int i = 0; i < s.size(); i++)
    11         {
    12             if (locs[s[i]] > idx)//如果当前字符出现过,那么当前子串的起始位置为这个字符上一次出现的位置+1
    13             {
    14                 idx = locs[s[i]];
    15             }
    16 
    17             if (i - idx > max)
    18             {
    19                 max = i - idx;
    20             }
    21 
    22             locs[s[i]] = i;
    23         }
    24         return max;
    25     }
    26 };

    其他解题方法:

     1 #include <bits/stdc++.h>
     2 #define MAX 110
     3 
     4 using namespace std;
     5 
     6 int pos[MAX], exist[MAX];
     7 
     8 int main()
     9 {
    10     string s;
    11     int lens,i,j,start,max_num;
    12     while(cin>>s)
    13     {
    14         lens=s.size();
    15         max_num=0,start=0;
    16         memset(pos,0,sizeof(pos));
    17         memset(exist,0,sizeof(exist));
    18         for(i=0;i<lens;i++)
    19         {
    20             if(exist[s[i]-'a'])
    21             {
    22                 for(j=start;j<=pos[s[i]-'a'];j++)
    23                     exist[s[j]-'a']=0;
    24                 start=pos[s[i]-'a']+1;
    25                 exist[s[i]-'a']=1;
    26                 pos[s[i]-'a']=i;
    27             }
    28             else
    29             {
    30                 exist[s[i]-'a']=1;
    31                 pos[s[i]-'a']=i;
    32                 max_num=max(max_num,i-start+1);
    33             }
    34         }
    35         printf("%d
    ",max_num);
    36     }
    37 }
  • 相关阅读:
    NET Core 2.2
    NET Core项目模板
    Eclipse同时显示多个控制台项目的输出
    Java中的序列化
    Java中的泛型
    Java中的集合
    Java中的数据结构
    Java中的包
    Java中的接口
    Java中的封装
  • 原文地址:https://www.cnblogs.com/zpfbuaa/p/5050220.html
Copyright © 2011-2022 走看看