首页 > 试题广场 >

无重复字符的最长子串

[编程题]无重复字符的最长子串
  • 热度指数:2667 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解

给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。


输入描述:

一行一个字符串,长度不超过1000



输出描述:

输出一个数字表示最长子串的长度

示例1

输入

abcabcbb

输出

3

说明

因为无重复字符的最长子串是"abc",所以其长度为3.


import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext())
        {
            String inPut = sc.next();
            String ansStr = "";
            int ans = 0;
            String temp = "";
            int temp1 = 0;
            for(int i = 0;i < inPut.length();i ++)
            {
                if(temp.indexOf(inPut.charAt(i)) == -1)
                {
                    temp += inPut.charAt(i);
                    temp1++;
                }else{
                    temp = "";
                    temp1 = 0;
                }
                if(ans < temp1)
                {
                    ans = temp1;
                }
            }
            System.out.println(ans);
        }
    }
}

发表于 2020-07-25 11:22:20 回复(1)
// 添加一个Go的代码
package main

import (
    "fmt"
    "os"
    "bufio"
)

func main(){
    reader := bufio.NewReader(os.Stdin)
    data,_,_ := reader.ReadLine()
    str := string(data)
    ans := 0
    start :=0 
    m := map[byte]int{}
    for i:=0;i<len(str);i++{
        ch := str[i]
        if _,has := m[ch];has{
            start = max(start,m[ch]+1)
        }
        ans = max(ans,i-start+1)
        m[ch] = i
    }
    fmt.Println(ans)
}
func max(a,b int)int{
    if a>b{return a}
    return b
}

发表于 2023-02-21 13:16:01 回复(0)
#字节跳动二面没写出来, 那就补补好啦, 小透明加油。
#其实这道题没有面试官说的那么简单的。。。小小抱怨一下。
def check_max(s):
    if  not s:
        return 0
    max_num=0 #记录最长字符串长度
    long_str="" #记录最长的字符串
    for index in range(len(s)):
        current=s[index] #当前字符
        if current not in long_str: #如果当前字符不在应该返回的最长的字符串里
            long_str+=current #最长的字符串加上当前字符串
            max_num=max(len(long_str),max_num) #最长的字符串加上当前字符串的长度和之前存储的最长的字符串的长度取最大值
        else:#如果当前字符已经在应该返回的最长的字符串里
            repeat_index=long_str.find(current)#找到这个重复的字符在最长的字符串里的位置

            #最长的字符串更新成该重复字符串之后的字符串加上该字符串
            # 例如"pwawbc"遇到第二个重复的w则变成: long_str[repeat_index+1:]:"a"+current"w"="aw"
            long_str=long_str[repeat_index+1:]+current
    return max_num

s=input()
print(check_max(s))
加油。
发表于 2020-09-08 19:34:59 回复(0)
var str = readline()
var res = 0
var newS = []
for(var i=0;i<str.length;i++){
    if(newS.indexOf(str[i]) == -1){
        newS.push(str[i])
    }else{
        newS.shift()
        i--
    }
    res = Math.max(res,newS.length)
}
console.log(res)

发表于 2020-08-13 11:40:28 回复(1)
import java.util.Scanner;
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextLine()) { // 注意 while 处理多个 case
System.out.println(lengthOfLongestSubString(in.nextLine()));
}
}
public static int lengthOfLongestSubString(String s) {
// write code here
if (s.length() == 0) {
return 0;
}
int left = 0;
int right = 0;
int maxLength = Integer.MIN_VALUE;
Map<Character, Integer> duplicateMap = new HashMap<>();
int length = s.length();
while (right < length) {
if (duplicateMap.containsKey(s.charAt(right))) {
duplicateMap.put(s.charAt(right), duplicateMap.get(s.charAt(right)) + 1);
} else {
duplicateMap.put(s.charAt(right), 1);
}

while (duplicateMap.containsKey(s.charAt(right)) &&
duplicateMap.get(s.charAt(right)) > 1) {
if (duplicateMap.containsKey(s.charAt(left))) {
// 退格子
duplicateMap.put(s.charAt(left), duplicateMap.get(s.charAt(left)) - 1);
}
left++;
}
maxLength = Math.max(maxLength, right - left + 1);
right++;
}
return maxLength;
}
}

经典滑动窗口法
编辑于 2024-01-02 10:06:25 回复(0)
#include <algorithm>
#include <iostream>
#include<string>
using namespace std;

int main() {
    string a;
    cin>>a;
    int l=a.length();
    int m=1;
    int start=0;
    //int tag=1;
    for(int end=1;end<l;end++){
        for(int j=end-1;j>=start;j--){
            if(a[end]==a[j]){
                start=j+1;
                break;
            }
        }
        m=max(m, end-start+1);
    }
    cout<<m<<endl;
}
// 64 位输出请用 printf("%lld")
发表于 2023-10-20 18:58:34 回复(0)
#include <stdio.h>
#include <string.h>
int main() {
   char str[1000];
   gets(str);
   int max=0;
   for (int i=0; i<strlen(str); i++) {
        int num[128]={0},j=i;
        for (; j<strlen(str); j++) {
            num[str[j]]++;
            if (num[str[j]]>=2) {
                break;
            }
        }
        max=max>(j-i)?max:(j-i);
   }
   printf("%d",max);
}

发表于 2023-08-31 22:15:29 回复(0)
const readline = require("readline");
 
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
});
rl.on("line", function (line) {
    let res: number = 0;
    let set = new Set();
    let rk: number = -1;
    for (let i = 0; i < line.length; i++) {
        if (i !== 0) {
            set.delete(line.charAt(i - 1));
        }
        while (rk + 1 < line.length && !set.has(line.charAt(rk + 1))) {
            set.add(line.charAt(rk + 1));
            ++rk;
        }
        res = Math.max(res, set.size);
    }
    console.log(res)//必须打印才能出正确的结果,无语
    return res;
});

发表于 2023-06-22 11:34:59 回复(0)
#include <iostream>
#include <bits/stdc++.h>
using namespace std;

int main() {
    string s;
    cin>>s;
    int sz = s.size();
    int maxlen = INT_MIN;
    unordered_map<char,int> charcount;
    for(int i=0;i<sz;i++){
        if(sz-i+1<maxlen) break;
        for(int j=i;j<sz;j++){
            if(charcount[s[j]]!=0) {
                int mapsize = charcount.size();
                maxlen = max(mapsize,maxlen);
                charcount.clear();
                break;
            }
            charcount[s[j]] = 1;
        }
        
    }
    cout<<maxlen<<endl;
}
// 64 位输出请用 printf("%lld")

发表于 2023-03-23 16:30:06 回复(0)
暴力破解
s = input()
if len(s) == 0:
    print(0)
else:
    arr = []
    for i in range(len(s)):
        for j in range(i,len(s)+1):
            #如果去重后长度与原截取的字符串相等,就是没有重复字符
            if len(set(s[i:j])) == len(s[i:j]):
                arr.append(j-i)
    print(max(arr))


发表于 2023-03-07 23:50:55 回复(0)
第一次忘记cout了
#include<iostream>
#include<unordered_set>
using namespace std;
class Solution{
    public:
    int LengthOfLongestSubString(string s){
        if(s.size()==0)return 0;
        unordered_set<char>lookup;
        int maxStr=0;
        int left =0;
        for(int i=0;i<s.size();i++){
            while(lookup.find(s[i])!=lookup.end()){
                lookup.erase(s[left]);
                left++;
            }
            maxStr=max(maxStr,i-left+1);
            lookup.insert(s[i]);
        }
        cout<<maxStr;
        return maxStr;
    }
};

int main(void){
    class Solution s;
    string Str;
    while(cin>>Str){
    s.LengthOfLongestSubString(Str);
    }
    return 0;
}

发表于 2022-10-02 19:09:05 回复(0)
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        Map<Character, Integer> map = new HashMap<>();
        
        String s = in.next();
        int res = 0;
        for (int start = 0, end = 0; end < s.length(); end ++ ) {
            char c = s.charAt(end);
            if (map.containsKey(c)) {
                start = Math.max(start, map.get(c));
            }
            res = Math.max(res, end - start + 1);
            map.put(s.charAt(end), end + 1);
        }
        System.out.println(res);
    }
}


发表于 2022-07-08 15:13:36 回复(0)
package main
import "fmt"
func main() {
    var s string
    fmt.Scanln(&s)
    maxLen := lengthOfLongestSubstring(s)
    fmt.Println(maxLen)
}
func lengthOfLongestSubstring(s string) int {
    n := len(s)
    if n < 2 {
        return n
    }
    maxLen := 1
    left, right := 0, 0
    win := make(map[byte]int)

    for right < n {
        next := 0
        if position, ok := win[s[right]]; ok {
            next = position
        }
        if next > left {
            left = next
        }
        maxLen = max(maxLen, right-left+1)
        win[s[right]] = right+1
        right++
    }
    return maxLen
}
func max(x, y int) int {
    if x < y {
        return y
    }
    return x
}
编辑于 2022-07-06 15:19:31 回复(0)
我的这个不正确吗?
<?php
function lengthOfLongestSubstring(String $str)
{
    $length = strlen($str);
    if ($length < 2) return $length;

    $temp = array();
    $start = 0;
    $maxLength = 0;
    $len_temp = 0;

    for ($i = 0; $i < $length; $i++) {
        $chr = $str[$i];

        if (array_key_exists($chr, $temp) && $temp[$chr] >= $start) {
            $start = $temp[$chr] + 1;
            $len_temp = $i - $temp[$chr];
        } else {
            $len_temp++;
            if ($len_temp > $maxLength) {
                $maxLength = $len_temp;
            }
        }
        $temp[$chr] = $i;
    }
    return $maxLength;
}
?>


发表于 2022-06-06 22:16:49 回复(0)
import java.util.*;

public class Main{
    public static void main(String[] args){
        
        Map<Character,Integer> map = new HashMap<>();
        Scanner sc = new Scanner(System.in);
        
        String s =sc.next();
        int left =0; int max=0;
        for(int i = 0; i< s.length();i++){
            if(      map.containsKey(    s.charAt(i)   )     ){
                left = Math.max(left, map.get(  s.charAt(i) )+1);
            }
            
            map.put(s.charAt(i),i);
            max = Math.max(max, i - left +1);
        
        }
        
        System.out.println(max);
    }
}

发表于 2022-03-22 09:53:47 回复(1)
data='abcabcbb'
c=[]
b=[]
foriiinrange(len(data)):
    foriin range(ii,len(data)):       
        ifdata[i]notinc:
             c.append(data[i])
        else:
            break
     
    data=data[len(c)-1::]
    b.append(len(c))
    c=[]
print(max(b))
发表于 2021-08-20 14:54:53 回复(0)
import java.util.*;

public class Main{
    
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            String str = sc.next();
            System.out.println(getMaxSubStrLen(str));
            return;
        }
    }
    
    public static int getMaxSubStrLen(String str){
        int left=0; 
        int right =0 ;
        Set<Character> window = new HashSet<>();
        int maxLen =0;
        while(right<str.length()){
            // 扩大窗口右边界
            Character c =str.charAt(right);
            right++;
            while(window.contains(c)){
                // 窗口包含右边新进入的元素,则移动左边界,缩小窗口
                window.remove(str.charAt(left));
                left++;
            }
            window.add(c);
            int windowLen = window.size();
            // 更新最大值
            maxLen = maxLen < windowLen ? windowLen : maxLen;
        }
 
        return maxLen;
    }
    
}

发表于 2021-04-20 02:17:32 回复(0)
def maxSubstr(s):
    d,start,ans={},0,0
    for i in range(len(s)):
        start = max(start,d.get(s[i],-1)+1)
        ans = max(ans,i-start+1)
        d[s[i]]=i
    return ans
s=input()
print(maxSubstr(s))

发表于 2021-03-18 01:31:04 回复(0)
function getMaxSubStrLength($str)
{
    // 非字符串或空字符串过滤
    if (!is_string($str) || empty($str)) {
        return -1;
    }
    
    // 最大子串长度
    $maxSubStrLength = 0;
    // 字符串长度
    $strLength = strlen($str);
    
    for ($i = 0; $i < $strLength; $i++) {
        // 子串
        $subStr = $str[$i];
        for ($j = $i + 1; $j < $strLength; $j++) {
            $res = strpos($subStr, $str[$j]);
            if (false === $res) {
                $subStr .= $str[$j];
            } else {
                break;
            }
        }

        $tempSubStrLength = strlen($subStr);
        if ($maxSubStrLength < $tempSubStrLength) {
            $maxSubStrLength = $tempSubStrLength;
        }

        // 效率:  如果最大子串长度已经大于剩余最长子串的长度,则后续不执行
        if ($maxSubStrLength >= $strLength - $i) {
            break;
        }
    }

    return $maxSubStrLength;
}

发表于 2021-02-25 13:56:45 回复(0)
看着容易自己一写错误错误,
循环考虑指针一定,在什么情况下移动
必须使用完毕后在移动
#include<iostream>
#include<vector>
using namespace std;

int lenghtOflongestSubstring(string input)
{
    int begin = 0; //不重复字符串开始位置
    int end = 0; //不重复字符串结束位置
    vector<int> hash(128,-1); //判断是否重复
    
    int ret =0 ;//返回结果
    char temp ;
    //这里必须程序循环,字符串操作就是遍历,别的不会
    
    while(end < input.size())
    {
       temp =input[end];
        
       //判断是否重复,并且在不重复序列内.;
        //【1,2,3 1 】
        //忘记 ==
        if (hash[temp] >= begin)
        {
            //[begin, end]   字符串存在重复,状态被破坏
             begin =hash[temp]+1; 
            
            // 类比快些排序双指针一定,这里移动是有条件的。if 情况下,这个必须考虑清楚
            //舍去左边部分,目的,我是顺序遍历,保证all情况
            
        }
        
        hash[temp] =end ;//update 
       // end++;//循环最容易忽视问题 是指针如何移动。for++ 不忘记while考虑清楚
        //
       ret = max(ret,end-begin+1); //忘记+1操作
        
      // 计算完毕,变化,指针这个地方,一看你没有注意到
        end++;//循环最容易忽视问题 是指针如何移动。
        
        
    }
    
    return ret;
}

//存在三个bug 忘记>= +1,END++位置不对

int main()
{   string temp;
    while(cin>>temp)
    {
         cout<< lenghtOflongestSubstring(temp)<<endl;
    }
}

发表于 2021-01-08 12:12:29 回复(0)