Home Web Front-end Front-end Q&A How to find non-repeating substrings in JavaScript

How to find non-repeating substrings in JavaScript

Apr 23, 2023 pm 07:30 PM

In actual development, we often need to perform some operations and processing on strings, one of which is to find non-repeating substrings. For example, in the string "abcabcbb", the longest non-repeating substring is "abc", and in the string "bbbbbb", the longest non-repeating substring is "b". These problems are known in algorithms as the "longest non-repeating substring" problem, and we can solve them using JavaScript.

1. Violent enumeration method

The simplest method is to use brute force enumeration method, that is, traverse the string from scratch for each character and add non-repeating characters one by one. substring until repeated characters are encountered. Then, record the length of the substring at this time, reset the substring, and continue traversing the string downward until the end of the traversal.

The code is as follows:

function longestSubstring(str) {
  let maxLength = 0; // 定义最大长度为 0
  for(let i = 0; i < str.length; i++) {
    let map = new Map(); // 定义 Map 来保存子串中元素出现的次数
    let length = 0; // 定义子串长度为 0
    for(let j = i; j < str.length; j++) {
      if(map.has(str[j])) { // 如果子串中已经有这个元素了
        maxLength = Math.max(maxLength, length); // 更新最大长度
        break; // 说明这个子串已经不符合要求了,跳出内部循环
      } else {
        map.set(str[j], 1); // 在 Map 中记录该元素的出现次数
        length++; // 子串长度 +1
        maxLength = Math.max(maxLength, length); // 更新最大长度
      }
    }
  }
  return maxLength;
}
Copy after login

The time complexity of this method is O(n^3). Since the number of nested loops is very large, it is not efficient when processing longer strings. Very low.

2. Sliding window method

In order to improve efficiency, we can use the sliding window method. The idea of ​​sliding window is to maintain a window of length k and slide this window to process strings. In this problem, the length of the sliding window is the length of the non-repeating string.

Specifically, when traversing a string, we define a starting pointer and an endpointer, and these two pointers will form a window. In each loop, if the element pointed to by the end pointer does not exist in the window, we can add it to the window, then expand the window and update the length of the window. If the element pointed to by the end pointer already exists in the window, we need to move the start pointer to the right and shrink the window until the element pointed to by the end pointer no longer exists in the window. In this process, we need to use a mapping table to record the number of occurrences of each element in the window.

The code is as follows:

function longestSubstring(str) {
  let maxLength = 0; // 定义最大长度为 0
  let map = new Map(); // 定义 Map 来保存元素出现的次数
  let left = 0; // 定义左指针为 0
  for(let right = 0; right < str.length; right++) {
    if(map.has(str[right])) { // 如果窗口内已经有该元素了
      left = Math.max(left, map.get(str[right]) + 1); // 更新左指针,向右移动
    }
    map.set(str[right], right); // 在 Map 中记录该元素的位置
    maxLength = Math.max(maxLength, right - left + 1); // 更新最大长度
  }
  return maxLength;
}
Copy after login

The time complexity of the sliding window method is O(n). It uses HashMap to quickly locate and store characters. It is faster and more efficient than the brute force enumeration method.

3. Summary

For the problem of the longest non-repeating substring in a string, we can use two methods to solve it: brute force enumeration method and sliding window method. The brute force enumeration method has a high time complexity, while the sliding window method is more efficient. In actual development, we can choose the appropriate method to solve the problem as needed.

The above is the detailed content of How to find non-repeating substrings in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do you connect React components to the Redux store using connect()? How do you connect React components to the Redux store using connect()? Mar 21, 2025 pm 06:23 PM

Article discusses connecting React components to Redux store using connect(), explaining mapStateToProps, mapDispatchToProps, and performance impacts.

React's Role in HTML: Enhancing User Experience React's Role in HTML: Enhancing User Experience Apr 09, 2025 am 12:11 AM

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

How do you define routes using the <Route> component? How do you define routes using the <Route> component? Mar 21, 2025 am 11:47 AM

The article discusses defining routes in React Router using the &lt;Route&gt; component, covering props like path, component, render, children, exact, and nested routing.

What are the limitations of Vue 2's reactivity system with regard to array and object changes? What are the limitations of Vue 2's reactivity system with regard to array and object changes? Mar 25, 2025 pm 02:07 PM

Vue 2's reactivity system struggles with direct array index setting, length modification, and object property addition/deletion. Developers can use Vue's mutation methods and Vue.set() to ensure reactivity.

What are Redux reducers? How do they update the state? What are Redux reducers? How do they update the state? Mar 21, 2025 pm 06:21 PM

Redux reducers are pure functions that update the application's state based on actions, ensuring predictability and immutability.

What are Redux actions? How do you dispatch them? What are Redux actions? How do you dispatch them? Mar 21, 2025 pm 06:21 PM

The article discusses Redux actions, their structure, and dispatching methods, including asynchronous actions using Redux Thunk. It emphasizes best practices for managing action types to maintain scalable and maintainable applications.

What are the benefits of using TypeScript with React? What are the benefits of using TypeScript with React? Mar 27, 2025 pm 05:43 PM

TypeScript enhances React development by providing type safety, improving code quality, and offering better IDE support, thus reducing errors and improving maintainability.

How can you use useReducer for complex state management? How can you use useReducer for complex state management? Mar 26, 2025 pm 06:29 PM

The article explains using useReducer for complex state management in React, detailing its benefits over useState and how to integrate it with useEffect for side effects.

See all articles