Maison interface Web js tutoriel Méditations LeetCode : sous-chaînes palindromiques

Méditations LeetCode : sous-chaînes palindromiques

Jul 21, 2024 am 09:16 AM

LeetCode Meditations: Palindromic Substrings

La description des sous-chaînes palindromiques est :

Étant donné une chaîne s, renvoie le nombre de sous-chaînes palindromiques qu'elle contient.

Une chaîne est un palindrome lorsqu'elle se lit de la même manière vers l'arrière et vers l'avant.

Une sous-chaîne est une séquence contiguë de caractères dans la chaîne.

Par exemple :

Input: s = "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".
Copier après la connexion

Ou :

Input: s = "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
Copier après la connexion

De plus, les contraintes indiquent que s est constitué de lettres anglaises minuscules.


Dans le problème précédent, nous avons trouvé une solution pour trouver la sous-chaîne palindromique la plus longue dans une chaîne donnée. Pour trouver un palindrome, nous avons utilisé une approche « développer par-dessus le centre », dans laquelle nous avons supposé que chaque caractère était le caractère central d'une sous-chaîne. Et, en conséquence, nous avons décalé les pointeurs gauche et droit.

Note
Checking a palindrome is easy with two pointers approach, which we've seen before with Valid Palindrome.

Compter les palindromes dans une sous-chaîne peut ressembler à ceci :

function countPalindromesInSubstr(s: string, left: number, right: number): number {
  let result = 0;
  while (left >= 0 && right < s.length && s[left] === s[right]) {
    result++;
    left--;
    right++;
  }

  return result;
}
Copier après la connexion

Tant que nous sommes dans les limites (gauche >= 0 && droite < s.length), nous vérifions si deux caractères à gauche et à droite sont identiques — si c'est le cas, nous mettons à jour notre résultat et décalons notre pointeurs.

Cependant, une fois que vous y réfléchissez, les indices sur lesquels les pointeurs sont initialisés sont importants. Par exemple, si nous passons la chaîne "abc" à countPalindromesInSubstr et que le pointeur gauche est à 0 tandis que le pointeur droit est au dernier index (2), alors notre résultat est simplement 0.

N'oubliez pas que nous supposons que chaque caractère est le caractère central d'une sous-chaîne, et comme chaque caractère est également une sous-chaîne, nous initialiserons nos pointeurs gauche et droit pour qu'ils pointent vers le caractère lui-même.

Note
A character by itself is considered palindromic, i.e., "abc" has three palindromic substrings: 'a', 'b' and 'c'.

Let's see how this process might look like.

If we have the string "abc", we'll first assume that 'a' is the middle of a substring:

"abc"

left = 0
right = 0
currentSubstr = 'a'

totalPalindromes = 1 // A single character is a palindrome
Copier après la connexion

Then, we'll try to expand the substring to see if 'a' can be the middle character of another substring:

"abc"

left = -1
right = 1
currentSubstr = undefined

totalPalindromes = 1
Copier après la connexion

Now that our left pointer is out of bounds, we can jump to the next character:

"abc"

left = 1
right = 1
currentSubstr = 'b'

totalPalindromes = 2
Copier après la connexion

Now, we'll update our pointers, and indeed, 'b' can be the middle character of another substring:

s = "abc"

left = 0
right = 2
currentSubstr = 'abc'

totalPalindromes = 2
Copier après la connexion

Well, currentSubstr is not a palindrome. Now we update our pointers again:

s = "abc"

left = -1
right = 3
currentSubstr = undefined

totalPalindromes = 2
Copier après la connexion

And, we're out of bounds again. Time to move on to the next character:

s = "abc"

left = 2
right = 2
currentSubstr = 'c'

totalPalindromes = 3
Copier après la connexion

Shifting our pointers, we'll be out of bounds again:

s = "abc"

left = 1
right = 3
currentSubstr = undefined

totalPalindromes = 3
Copier après la connexion

Now that we've gone through each character, our final result of totalPalindromes is, in this case, 3. Meaning that there are 3 palindromic substrings in "abc".

However, there is an important caveat: each time we assume a character as the middle and initialize two pointers to the left and right of it, we're trying to find only odd-length palindromes. In order to mitigate that, instead of considering a single character as the middle, we can consider two characters as the middle and expand as we did before.

In this case, the process of finding the even-length substring palindromes will look like this — initially, our right pointer is left + 1:

s = "abc"

left = 0
right = 1
currentSubstr = 'ab'

totalPalindromes = 0
Copier après la connexion

Then, we'll update our pointers:

s = "abc"

left = -1
right = 2
currentSubstr = undefined

totalPalindromes = 0
Copier après la connexion

Out of bounds. On to the next character:

s = "abc"

left = 1
right = 2
currentSubstr = 'bc'

totalPalindromes = 0
Copier après la connexion

Updating our pointers:

s = "abc"

left = 0
right = 3
currentSubstr = undefined

totalPalindromes = 0
Copier après la connexion

The right pointer is out of bounds, so we go on to the next character:

s = "abc"

left = 2
right = 3
currentSubstr = undefined

totalPalindromes = 0
Copier après la connexion

Once again we're out of bounds, and we're done going through each character. There are no palindromes for even-length substrings in this example.


We can write a function that does the work of counting the palindromes in each substring:

function countPalindromes(s: string, isOddLength: boolean): number {
  let result = 0;
  for (let i = 0; i &lt; s.length; i++) {
    let left = i;
    let right = isOddLength ? i : i + 1;
    result += countPalindromesInSubstr(s, left, right);
  }

  return result;
}
Copier après la connexion

In our main function, we can call countPalindromes twice for both odd and even length substrings, and return the result:

function countSubstrings(s: string): number {
  let result = 0;
  result += countPalindromes(s, true); // Odd-length palindromes
  result += countPalindromes(s, false); // Even-length palindromes

  return result;
}
Copier après la connexion

Overall, our solution looks like this:

function countSubstrings(s: string): number {
  let result = 0;
  result += countPalindromes(s, true); // Odd-length palindromes
  result += countPalindromes(s, false); // Even-length palindromes

  return result;
}

function countPalindromes(s: string, isOddLength: boolean): number {
  let result = 0;
  for (let i = 0; i &lt; s.length; i++) {
    let left = i;
    let right = isOddLength ? i : i + 1;
    result += countPalindromesInSubstr(s, left, right);
  }

  return result;
}

function countPalindromesInSubstr(s: string, left: number, right: number): number {
  let result = 0;
  while (left &gt;= 0 &amp;&amp; right &lt; s.length &amp;&amp; s[left] === s[right]) {
    result++;
    left--;
    right++;
  }

  return result;
}
Copier après la connexion

Time and space complexity

The time complexity is O(n2)O(n^2) O(n2) as we go through each substring for each character (countPalindromes is doing an O(n2)O(n^2) O(n2) operation, we call it twice separately.)
The space complexity is O(1)O(1) O(1) as we don't have an additional data structure whose size will grow with the input size.


Next up is the problem called Decode Ways. Until then, happy coding.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn

Article chaud

Repo: Comment relancer ses coéquipiers
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
Combien de temps faut-il pour battre Split Fiction?
3 Il y a quelques semaines By DDD
R.E.P.O. Crystals d'énergie expliqués et ce qu'ils font (cristal jaune)
1 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: Comment obtenir des graines géantes
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌

Article chaud

Repo: Comment relancer ses coéquipiers
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
Combien de temps faut-il pour battre Split Fiction?
3 Il y a quelques semaines By DDD
R.E.P.O. Crystals d'énergie expliqués et ce qu'ils font (cristal jaune)
1 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: Comment obtenir des graines géantes
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌

Tags d'article chaud

Bloc-notes++7.3.1

Bloc-notes++7.3.1

Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise

SublimeText3 version chinoise

Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1

Envoyer Studio 13.0.1

Puissant environnement de développement intégré PHP

Dreamweaver CS6

Dreamweaver CS6

Outils de développement Web visuel

SublimeText3 version Mac

SublimeText3 version Mac

Logiciel d'édition de code au niveau de Dieu (SublimeText3)

Remplacer les caractères de chaîne en javascript Remplacer les caractères de chaîne en javascript Mar 11, 2025 am 12:07 AM

Remplacer les caractères de chaîne en javascript

Tutoriel de configuration de l'API de recherche Google personnalisé Tutoriel de configuration de l'API de recherche Google personnalisé Mar 04, 2025 am 01:06 AM

Tutoriel de configuration de l'API de recherche Google personnalisé

Exemple Couleurs Fichier JSON Exemple Couleurs Fichier JSON Mar 03, 2025 am 12:35 AM

Exemple Couleurs Fichier JSON

8 Superbes plugins de mise en page JQuery Page 8 Superbes plugins de mise en page JQuery Page Mar 06, 2025 am 12:48 AM

8 Superbes plugins de mise en page JQuery Page

10 Highlighters de syntaxe jQuery 10 Highlighters de syntaxe jQuery Mar 02, 2025 am 12:32 AM

10 Highlighters de syntaxe jQuery

Créez vos propres applications Web Ajax Créez vos propres applications Web Ajax Mar 09, 2025 am 12:11 AM

Créez vos propres applications Web Ajax

Qu'est-ce que & # x27; ceci & # x27; en javascript? Qu'est-ce que & # x27; ceci & # x27; en javascript? Mar 04, 2025 am 01:15 AM

Qu'est-ce que & # x27; ceci & # x27; en javascript?

10 tutoriels JavaScript & jQuery MVC 10 tutoriels JavaScript & jQuery MVC Mar 02, 2025 am 01:16 AM

10 tutoriels JavaScript & jQuery MVC

See all articles