leetcode系列(双语)003——GO无重复字符的最长子串

文章目录

  • 003、Longest Substring Without Repeating Characters
  • 个人解题
  • 官方解题
  • 扩展

003、Longest Substring Without Repeating Characters

无重复字符的最长子串

Given a string s, find the length of the longest substring without repeating characters.

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

Example :
Input: s = “abcabcbb”
Output: 3
Explanation: The answer is “abc”, with the length of 3.

示例:
输入: s = “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。

个人解题

func lengthOfLongestSubstring(s string) int {m := make(map[uint8]int)//记录当前字符的长度strLen := 0//记录最大的字符的长度maxStrLen := 0//计算字符的长度的开始下标start := 0for i := 0; i < len(s); i++ {//查询判断m是否存在字符temp := m[s[i]]if temp == 0 {//不存在,保存记录m[s[i]] = 1//当前长度+1strLen++} else {//存在重复字符串//判断当前长度是否超过最大长度if strLen > maxStrLen {maxStrLen = strLen}//重置strLen = 0if start < len(s) {i = startm = make(map[uint8]int)} else {break}start++}}//判断当前长度是否超过最大长度if strLen > maxStrLen {maxStrLen = strLen}return maxStrLen
}

在这里插入图片描述

官方解题

func lengthOfLongestSubstring(s string) int {// 哈希集合,记录每个字符是否出现过m := map[byte]int{}n := len(s)// 右指针,初始值为 -1,相当于我们在字符串的左边界的左侧,还没有开始移动rk, ans := -1, 0for i := 0; i < n; i++ {if i != 0 {// 左指针向右移动一格,移除一个字符delete(m, s[i-1])}for rk + 1 < n && m[s[rk+1]] == 0 {// 不断地移动右指针m[s[rk+1]]++rk++}// 第 i 到 rk 个字符是一个极长的无重复字符子串ans = max(ans, rk - i + 1)}return ans
}func max(x, y int) int {if x < y {return y}return x
}

扩展

Given a string, print the longest substring without repeating characters in Golang. For example, the longest substrings without repeating characters for “ABDEFGABEF” are “BDEFGA”.

Examples:

Input : GEEKSFORGEEKS
Output :
Substring: EKSFORG
Length: 7

Input : ABDEFGABEF
Output :
Substring: BDEFGA
Length: 6
The idea is to traverse the string and for each already visited character store its last occurrence in an array pos of integers(we will update the indexes in the array based on the ASCII values of the characters of the string). The variable st stores starting point of current substring, maxlen stores length of maximum length substring, and start stores starting index of maximum length substring.

While traversing the string, check whether the current character is already present in the string by checking out the array pos. If it is not present, then store the current character’s index in the array with value as the current index. If it is already present in the array, this means the current character could repeat in the current substring. For this, check if the previous occurrence of character is before or after the starting point st of the current substring. If it is before st, then only update the value in array. If it is after st, then find the length of current substring currlen as i-st, where i is current index.

Compare currlen with maxlen. If maxlen is less than currlen, then update maxlen as currlen and start as st. After complete traversal of string, the required longest substring without repeating characters is from s[start] to s[start+maxlen-1].

// Golang program to find the length of the
// longest substring without repeating
// characters

package main

import “fmt”

func longest_substring(s string, n int) string {

var i int// starting point of 
// current substring. 
st := 0     // length of current substring.   
currlen := 0  // maximum length substring  
// without repeating  characters 
maxlen := 0   // starting index of  
// maximum length substring. 
start := 0 // this array works as the hash table 
// -1 indicates that element is not 
// present before else any value  
// indicates its previous index 
pos := make([]int, 125) for i = 0; i < 125; i++ { pos[i] = -1 
} // storing the index 
// of first character 
pos[s[0]] = 0 for i = 1; i < n; i++ { // If this character is not present in array, // then this is first occurrence of this // character, store this in array. if pos[s[i]] == -1 { pos[s[i]] = i } else { // If this character is present in hash then // this character has previous occurrence, // check if that occurrence is before or after // starting point of current substring. if pos[s[i]] >= st { // find length of current substring and // update maxlen and start accordingly. currlen = i - st if maxlen < currlen { maxlen = currlen start = st } // Next substring will start after the last // occurrence of current character to avoid // its repetition. st = pos[s[i]] + 1 } // Update last occurrence of // current character. pos[s[i]] = i } } 
// Compare length of last substring  
// with maxlen and update maxlen  
// and start accordingly. 
if maxlen < i-st { maxlen = i - st start = st 
} // the required string 
ans := ""// extracting the string from  
// [start] to [start+maxlen] 
for i = start; i < start+maxlen; i++ { ans += string(s[i]) 
} return ans 

}

func main() {

var s string = "GEEKSFORGEEKS"
var n int = len(s) // calling the function to  
// get the required answer. 
var newString = longest_substring(s, n) // finding the length of the string 
var length int = len(newString) fmt.Println("Longest substring is: ", newString) 
fmt.Println("Length of the string: ", length) 

}
Output:

Longest substring is: EKSFORG
Length of the string: 7
Note: Instead of using the array, we can also use a map of string to int.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out - check it out now!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/192680.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

解决:ERROR: No matching distribution found for PIL

解决&#xff1a;ERROR: No matching distribution found for PIL 背景 在搭建之前的代码环境时&#xff0c;报错&#xff1a; ERROR: Could not find a wersion that satisfies the requirement PIL&#xff08;from versions: none&#xff09; ERROR: No matching distribu…

wpf devexpress 创建布局

模板解决方案 例子是一个演示连接数据库连接程序。打开RegistrationForm.BaseProject项目和如下步骤 RegistrationForm.Lesson1 项目包含结果 审查Form设计 使用LayoutControl套件创建混合控件和布局 LayoutControl套件包含三个主控件&#xff1a; LayoutControl - 根布局…

【机器学习算法】机器学习:支持向量机(SVM)

转载自&#xff1a; 【精选】机器学习&#xff1a;支持向量机&#xff08;SVM&#xff09;-CSDN博客 1.概述 1.1&#xff0c;概念 支持向量机&#xff08;SVM&#xff09;是一类按监督学习方式对数据进行二元分类的广义线性分类器&#xff0c;其决策边界是对学习样本求解的最…

WordPress主题WoodMart v7.3.2 WooCommerce主题和谐汉化版下载

WordPress主题WoodMart v7.3.2 WooCommerce主题和谐汉化版下载 WoodMart是一款出色的WooCommerce商店主题&#xff0c;它不仅提供强大的电子商务功能&#xff0c;还与流行的Elementor页面编辑器插件完美兼容。 主题文件在WoodMart Theme/woodmart.7.3.2.zip&#xff0c;核心在P…

公共字段自动填充-Mybatis Plus实现

简历描述 使用ThreadLocal动态获取当前登录用户&#xff0c;从而解决MybatisPlus公共字段自动填充问题。达到简化编码的目的&#xff0c;使业务方法更加简洁。 问题分析 前面我们已经完成了后台系统的员工管理功能的开发&#xff0c;在新增员工时需要设置创建时间、创建人、…

每天一点python——day69

#字符串的比较操作使用的符号&#xff1a; >[大于]&#xff0c;>[大于等于]&#xff0c;<[小于]&#xff0c;<[小于等于]&#xff0c;[等于]&#xff0c;![不等于]#如图&#xff1a; #例子&#xff1a;比较原理释义&#xff1a;每个字符在计算机里面都有一个原始值…

基于STM32的多组外部中断(EXTI)的优化策略与应用

在某些嵌入式应用中&#xff0c;可能需要同时处理多个外部中断事件。STM32系列微控制器提供了多组外部中断线&#xff08;EXTI Line&#xff09;&#xff0c;可以同时配置和使用多个GPIO引脚作为外部中断触发器。为了有效管理和处理多组外部中断&#xff0c;我们可以采取一些优…

【c++】——类和对象(中)——实现完整的日期类(优化)万字详细解疑答惑

作者:chlorine 专栏:c专栏 赋值运算符重载()()():实现完整的日期类(上) 我走的很慢&#xff0c;但我从不后退。 【学习目标】 日期(- - --)天数重载运算符 日期-日期 返回天数 对日期类函数进行优化(不符合常理的日期&#xff0c;负数&#xff0c;const成员)c中重载输入cin和输…

python趣味编程-5分钟实现一个益智数独游戏(含源码、步骤讲解)

Puzzle Game In Python是用 Python 编程语言Puzzle Game Code In Python编写的,有一个 4*4 的棋盘,有 15 个数字。然后将数字随机洗牌。 在本教程中,我将教您如何使用Python 创建记忆谜题游戏。 Python Puzzle Game游戏需要遵循以下步骤,首先是将图块数量移动到空的图块空…

机器视觉系统选型-定光照强度

同一个外形结构的光源&#xff0c;光照强度受如下影响&#xff1a; 单颗灯珠的亮度灯珠排列的数量和密度漫射板/防护板的材质&#xff08;透明、半透明、全漫射&#xff09; 在合理范围内提升光照强度&#xff0c;可降低对相机曝光时长的要求 外形结构尺寸相同的两款光源&am…

uni-app(1)pages. json和tabBar

第一步 在HBuilderX中新建项目 填写项目名称、确定目录、选择模板、选择Vue版本&#xff1a;3、点击创建 第二步 配置pages.json文件 pages.json是一个非常重要的配置文件&#xff0c;它用于配置小程序的页面路径、窗口表现、导航条样式等信息。 右键点击pages&#xff0c;按…

【C++入门到精通】右值引用 | 完美转发 C++11 [ C++入门 ]

阅读导航 引言一、左值引用和右值引用1. 什么是左值&#xff1f;什么是左值引用&#xff1f;2. 什么是右值&#xff1f;什么是右值引用&#xff1f;3. move( )函数 二、左值引用与右值引用比较三、右值引用使用场景和意义四、完美转发std::forward 函数完美转发实际中的使用场景…