LeetCode(3) Longest Substring Without Repeating Characters

这篇博客介绍了如何解决LeetCode的第3题,即寻找给定字符串中最长的不包含重复字符的子串。讨论了两种算法,一种是时间复杂度为O(N²)的解决方案,另一种是更高效的O(N)算法。博主强调了O(N)算法的细节,包括使用两个指针i和j搜索,以及在循环外更新maxLen的重要性。还提到了动态规划与哈希结合的解法会导致超时,因此推荐使用O(N)方法。
摘要由CSDN通过智能技术生成

LeetCode的第3题,给定一个字符串,找到其中的一个最长的字串,使得这个子串不包含重复的字符。

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

1 时间复杂度O(N²)的算法

//
//  Solution.h
//  LeetCodeOJ_003_LongestUniqueSubstr
//
//  Created by feliciafay on 11/21/13.
//  Copyright (c) 2013 feliciafay. All rights reserved.
//

#ifndef LeetCodeOJ_003_LongestUniqueSubstr_Solution_h
#define LeetCodeOJ_003_LongestUniqueSubstr_Solution_h
#include <iostream>
#include <string>
#include <map>
using std::string;

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        
        unsigned long limit =s.length();
        if(limit==0)
            return 0;
        int start = 0;
        int p = 0;
        int q = 0; //q对程序其实没作用,主要用来debug的时候观察。q与p的区别是,p表示当前进行探测的字符,q表示p的前面一位字符。
        unsigned long max_length = 1;
        unsigned long cur_length = 1;
        string sub1;
        std::map<char,int> char_int_map;
        std::map<char,int>::iterator it = char_int_map.begin();
        while(p<limit) {
            it = char_int_map.find(s[p]);
            if(it == char_int_map.end()) {
                q = p;
//                std::cout<<"1-1 q: "<<q<<std::endl;
                char_int_map.insert(std::p
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值