首页 > 其他分享 >手撕代码——最长不包含重复字符的字符串长度

手撕代码——最长不包含重复字符的字符串长度

时间:2022-10-26 20:08:35浏览次数:86  
标签:字符 int MapArray answer length Result 字符串 RepeatedIndex 最长


3. Longest Substring Without Repeating Characters

Medium

6059348FavoriteShare

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.


class Solution {
public:
int lengthOfLongestSubstring(string s) {
int Result = 0;int RepeatedIndex = -1;
if(s.length() == 0){return Result;}
map<char,int> MapArray;
for(int i = 0;i < s.length();i ++){
if(MapArray.find(s[i]) != MapArray.end() && MapArray[s[i]] > RepeatedIndex){
RepeatedIndex = MapArray[s[i]];
}
if((i - RepeatedIndex) > Result){
Result = i - RepeatedIndex;
}
MapArray[s[i]] = i;
}
return Result;
}
};

 

标签:字符,int,MapArray,answer,length,Result,字符串,RepeatedIndex,最长
From: https://blog.51cto.com/u_13121994/5798280

相关文章

  • 最长递增子序列
    题目描述给定一个序列An=a1,a2, ...,an,找出最长的子序列使得对所有i<j,ai<aj。求出这个子序列的长度输入描述:输入的序列输出描述:最长递增子序列的长度示......
  • 字符串“同素异形体”可以用key-value的unordered_map存储
    49. GroupAnagramsMedium1896123FavoriteShareGivenanarrayofstrings,groupanagramstogether.Example:Input:​​["eat","tea","tan","ate","nat","bat"]​......
  • 字符串--通配符*匹配
    44. WildcardMatchingHard120177FavoriteShareGivenaninputstring(​​s​​​)andapattern(​​p​​​),implementwildcardpatternmatchingwithsupportf......
  • 求两个字符串的最长公共子字符串长度
    题目描述给定两个字符串,请编写代码,输出最长公共子串(LongestCommonSubstring),是指两个字符串中的最长的公共子串,要求子串一定是连续。输入描述:文本格式,2个非空字符串(字母......
  • 最长对称子字符串
    题目描述给定一个字符串(数字或大小写字母),找出最长的对称的子串(如有多个,输出任意一个)。例如:输入:“abbaad”输出:“abba”输入描述:字符串输出描述:字符串示例1输入复制......
  • 字符串转换整数 (atoi)
    请你来实现一个 myAtoi(strings) 函数,使其能将字符串转换成一个32位有符号整数(类似C/C++中的atoi函数)。函数 myAtoi(strings)的算法如下:读入字符串并丢弃无......
  • 递归求字符串长度
    #define_CRT_SECURE_NO_WARNINGS1#include<stdio.h>intmy_strlen(char*st){  if(*st!='\0') {  return1+my_strlen(st+1); } else return0;}......
  • C#解析Cookie字符串为CookieCollection
    C#解析Cookie字符串为CookieCollection publicstaticCookieCollectionGetAllCookiesFromHeader(stringstrHeader,stringstrHost){ArrayListal=......
  • 自定义函数求字符串长度
    #define_CRT_SECURE_NO_WARNINGS1#include<stdio.h>intmy_strlen(char*st){ intcount=0; while(*st!='\0') {  count++; *st++; } returncount......
  • 最长公共子串
    ​​参考LCS通解​​题目描述牛牛拿到了一个藏宝图,顺着藏宝图的指示,牛牛发现了一个藏宝盒,藏宝盒上有一个机关,机关每次会显示两个字符串s和t,根据古老的传说,牛牛需要每次都......