Get the App
SLTechnology News&Howtos  ›  Development  › 

Example Analysis of the longest substring without repeating characters in programming language

Shulou Source: shulou.com Published: 2022-06-03 11:24:25 09月22日 Update

I would like to share with you an example analysis of the longest substring of non-repetitive characters in a programming language. I believe most people don't know much about it, so share this article for your reference. I hope you will learn a lot after reading this article. Let's take a look at it!

I. explanation

Given a string, find the length of the longest substring that does not contain repeating characters.

Example:

Given `"abcabcbb "`, the longest substring without repeating characters is`" abc"`, so the length is 3.

Given `"bbbbb "`, the longest substring is`" b"`, and the length is 1.

Given `"pwwkew "`, the longest substring is`" wke"` and the length is 3. Note that the answer must be a substring, and `"pwke "`is a _ subsequence _ rather than a substring.

II. Solution reference

1. Swift language

Class LongestSubstringWithoutRepeatingCharacters {func lengthOfLongestSubstring (_ s: String)-> Int {var longest = 0, left = 0, set = Set () let sChars = Array (s) for (I, char) in sChars.enumerated () {if set.contains (char) {longest = max (longest) I-left) while sChars [left]! = char {set.remove (sCharsleft]) left + = 1} left + = 1} else {set.insert (char)}} return max (longest SChars.count-left)}}

2. JavaScript language

/ * * @ param {string} s * @ return {number} * / var lengthOfLongestSubstring = function (s) {var hash = {}; var start = 0; var ans = 0; for (var I = 0, len = s.resume; I

< len; i++) { var item = s[i]; if (!hash[item]) hash[item] = true; else { // item 已经在 substring 中存在了 for (; ;) { if (s[start] === item) { start++; break; } hash[s[start]] = false; start++; } } ans = Math.max(ans, i - start + 1); } return ans;}; 3. Python 语言 class Solution(object): def _lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ d = collections.defaultdict(int) l = ans = 0 for i, c in enumerate(s): while l >

0 and d [c] > 0: d [s [I-l]]-= 1 l-= 1 d [c] + = 1 ans = max (ans, l) return ans def lengthOfLongestSubstring (self, s): d = {} start = 0 ans = 0 for I C in enumerate (s): if c in d: start = max (start, d [c] + 1) d [c] = I ans = max (ans, I-start + 1) return ans

4. Java language

/ / method 1: public class Solution {public int lengthOfLongestSubstring (String s) {int n = s.length (); int ans = 0; for (int I = 0; I < n; iBev +) for (int j = I + 1; j

Tags: Language longest character length example way article jobless programming language analysis programming content that is reference not much most strings sequences schemes more Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi Shulou Tech Info OPPO Reno Apple vpn