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 }
  • 相关阅读:
    vue项目搭建步骤
    文件的操作总结
    WPF 使用皮肤影响按钮自定义
    WPF中:未找到可以 register Name“XXX”的 NameScope
    WPF Label或者其他控件(以Content显示内容的)单个下划线不显示的问题。
    wpf 中GridControl后面总是多一空白列
    WPF设置控件层次问题(最顶层,最底层)
    WPF中设置TreeView的高度随着窗口改变
    C# 检测文件是否被其他进程占用
    XML文件的操作
  • 原文地址:https://www.cnblogs.com/zpfbuaa/p/5050220.html
Copyright © 2011-2022 走看看