3. Longest Substring Without Repeating Characters(无重复字符的最长子串)

qlmx
qlmx
qlmx
54
文章
2
评论
2020年2月14日23:45:32 评论 873阅读2分42秒

3. Longest Substring Without Repeating Characters(无重复字符的最长子串)

1 问题描述

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.

2 C++

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int begin = 0;
        int result = 0;
        string word = "";
        int word_map[128] = {0};
        for(int i=0; i<s.length(); i++) {
            word_map[ s[ i ] ]++;
            if(word_map[ s[ i ] ] == 1) {
                word += s[i];
                if(result < word.length())
                    result = word.length();
            }
            else {
                while(begin < i && word_map[ s [ i ] ] > 1) {
                    word_map[ s[ begin ] ]--;
                    begin++;
                }
                word = "";
                for(int j=begin; j<=i; j++) {
                    word += s[j];
                }
            }
        }
        return result;

    }
};
继续阅读
  • 我的微信小程序
  • 这是我的微信小程序扫一扫
  • weinxin
  • 我的微信公众号
  • 我的微信公众号扫一扫
  • weinxin
leetcode最后更新:2020年2月15日
qlmx
  • 本文由 发表于 2020年2月14日23:45:32
  • 除非特殊声明,本站文章均为原创,转载请务必保留本文链接
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: