LeetCode(03 Longest Substring Without Repeating Characters)

简介

Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: “abcabcbb”
Output: 3
Explanation: The answer is “abc”, with the length of 3.
Example 2:
Input: “bbbbb”
Output: 1
Explanation: The answer is “b”, with the length of 1.
Example 3:
Input: “pwwkew”
Output: 3
Explanation: 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.

解题思路

类似于桶排序,将每一个字符对应的ASII码依依进行匹配。
初始化数组为0,从第一个字符开始匹配,若数组为0,说明没有匹配到,将其置为1;
若为1,即匹配的已存在,则说明出现重复;
记录当前子串数,从第二个字符开始重新匹配,直到把整个字符串匹配完

代码

#include <iostream>
#include <string>
#include <memory.h>
using namespace std;

class Solution {
public:

    int lengthOfLongestSubstring(string s) {
        int num[127] = {0};                         //对应ASII码
       // printArray(num);
       // cout << endl;
        int n = 0;                                  //记录每次最大的子串数
        int strlen = s.length();                    //字符串长度
        cout << "strlen:" << strlen << endl;
        for(int i = 0; i < strlen; i++)
        {
            for(int j = i; j < strlen; j++)
            {
               // if(num[(int)s[j]-97] == 0)
               if(num[(int)s[j]] == 0)              //未出现重复
                {
                   // num[(int)s[j]-97] = 1;
                    num[(int)s[j]] = 1;
                    //printArray(num);
                   // cout << "frist: " << endl;
                    n++;
                    if(length < n)
                    {
                    length = n;
                    }
                   // cout << "length:" << length << " " << "n:" << n << endl;
                }
                else                                //出现重复
                {
                    memset(num, 0, sizeof(num));    //将数组num全置为0
                  //  printArray(num);
                   // cout << "sencond: " << endl;
                    n = 0;
                    break;
                }
            }
        }
        return length;
    }
    void printArray(int num[]) //遍历数组
    {
        for(int i = 0; i < 127; i++)
        {
            cout << num[i] << " ";
        }
    }
private:
    int length = 0;
};

int main()
{
    string str;
    cin >> str;
    Solution su;
 //   cout << endl;
    cout << su.lengthOfLongestSubstring(str);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值