zoukankan      html  css  js  c++  java
  • LeetCode——无重复字符的最长子串

    题目地址:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/

    解题思路:采用滑动窗口算法,在窗口内的字符串就是不重复子串,每次判断新的字符时,看窗口内是否存在该字符,如果存在,那么剔除并重新调整窗口左边界边界;如果不存在,那么添加到窗口内,窗口右边界++。

    值得注意的样例

    >>>" " \空格
    
    >>>"abba"

    具体代码:

    int lengthOfLongestSubstring(char * s) {
        int maxLen = 0;
        int tmpLen = 0;//记录当前子串长度
        int winL, winR;//滑动窗口边界
        int i, j;
        winL = 0;
        winR = -1;
    
        int len = strlen(s);
        bool check[256];
        memset(check, 0, sizeof(check));
        //出现空格字符串的情况
        if (strcmp(s, " ") == 0)
            return 1;
        for (i = 0; i < len; i++) {
            //如果没有出现,加入窗口
            if (!check[(int)s[i]]) {
                winR++;
                check[(int)s[i]] = true;
            }
            //查找第一次出现的位置
            else {
                for (j = i - 1; j >= 0; j--)
                    if (s[j] == s[i])
                        break;
            //如果该位置在窗口内,那么剔除
                if (j >= winL) {
                    winL = j + 1;
                    winR = i;
                }
            //不在窗口内,直接加入
                else 
                    winR++;
            }
            tmpLen = winR - winL + 1;
            maxLen = maxLen < tmpLen ? tmpLen : maxLen;
        }
        return maxLen;
    }

    暴力解法(超时):逐个遍历,如果出现重复,那么i回退到i-tmplen重新遍历

    int lengthOfLongestSubstring(char * s){
        int maxLen=0;
        int tmpLen=0;//记录当前子串长度
        bool check[256];
        memset(check,0,sizeof(check));
        for(int i=0;i<(int)strlen(s);i++){
            if(!check[(int)s[i]]){
                check[(int)s[i]]=true;
                tmpLen++;
            }
            else{
                maxLen=maxLen<tmpLen?tmpLen:maxLen;
                memset(check,0,sizeof(check));
                i=i-tmpLen;
                tmpLen=0;
            }
        }
        maxLen=maxLen<tmpLen?tmpLen:maxLen;
        if(strcmp(s," ")==0)
            maxLen=1;
        return maxLen;
    }
  • 相关阅读:
    String与int转换,Java当中
    微信小程序首页的上一个页面栈和当前页面栈
    windows中用命令行实现http下载网络文件
    jmeter
    java
    java
    java请求python的x-www-form-urlencoded接口
    java
    getopts/getopt命令行参数处理
    failed command: READ FPDMA QUEUED
  • 原文地址:https://www.cnblogs.com/cc-xiao5/p/13255941.html
Copyright © 2011-2022 走看看