Como verificar se uma string é um palíndromo

Como verificar se uma string é um palíndromo

Uma corda é considerada um palíndromo se a corda original e seu reverso forem iguais. Neste artigo, você aprenderá sobre o algoritmo para determinar se a string fornecida é um palíndromo ou não. Você também aprenderá como implementar esse algoritmo nas linguagens de programação mais populares, como C ++, Python, C e JavaScript.





Exemplos de Palíndromo String

Abaixo estão alguns exemplos de strings palíndromo e não palíndromo:





Algoritmo para determinar se uma determinada string é um palíndromo ou não

Algoritmos são simplesmente uma série de instruções que são seguidas, passo a passo, para fazer algo útil ou resolver um problema. Você pode resolver o problema do palíndromo de strings usando o algoritmo abaixo:





  1. Declare uma função que aceita a string fornecida como parâmetro.
  2. Crie uma variável booleana e defina-a como verdadeira. Deixe a variável ser bandeira .
  3. Encontre o comprimento da string fornecida. Deixe o comprimento ser n .
  4. Converta a string fornecida em minúsculas para fazer a comparação entre os caracteres que não diferenciam maiúsculas de minúsculas.
  5. Inicialize a variável de baixo índice como baixo e defina-o como 0.
  6. Inicialize a variável de alto índice como Alto e defina-o como n-1.
  7. Faça o seguinte enquanto o baixo for menor que o alto:
    • Compare caracteres de índice baixo e índice alto.
    • Se os caracteres não corresponderem, defina o sinalizador como falso e interrompa o loop.
    • Aumente o valor de baixo em 1 e diminua o valor de alto em 1.
  8. Se o sinalizador for verdadeiro no final da função, significa que a string fornecida é um palíndromo.
  9. Se o sinalizador for falso no final da função, significa que a string fornecida não é um palíndromo.

Programa C ++ para verificar se uma determinada string é um palíndromo ou não

Abaixo está a implementação C ++ para determinar se a string fornecida é um palíndromo ou não:

você precisa do ps plus para jogar fortnite
// Including libraries
#include
using namespace std;
// Function to check string palindrome
void checkPalindrome(string str)
{
// Flag to check if the given string is a palindrome
bool flag = true;

// Finding the length of the string
int n = str.length();

// Converting the string to lowercase
for(int i = 0; i {
str[i] = tolower(str[i]);
}

// Initializing low index variable
int low = 0;

// Initializing high index variable
int high = n-1;

// Running the loop until high is greater than low
while (high > low)
{
// If the characters are not same, set the flag to false
// and break from the loop
if(str[high] != str[low])
{
flag = false;
break;
}

// Increment the low index variable
low++;

// Decrement the high index variable
high--;
}

// Check if flag is true or false
if (flag)
{
cout << 'Yes, the given string is a palindrome' << endl;
}
else
{
cout << 'No, the given string is not a palindrome' << endl;
}

return;

}
int main()
{
// Test case: 1
string str1 = 'MUO';
checkPalindrome(str1);

// Test case: 2
string str2 = 'madam';
checkPalindrome(str2);

// Test case: 3
string str3 = 'MAKEUSEOF';
checkPalindrome(str3);

// Test case: 4
string str4 = 'racecar';
checkPalindrome(str4);

// Test case: 5
string str5 = 'mom';
checkPalindrome(str5);

return 0;
}

Saída:



No, the given string is not a palindrome
Yes, the given string is a palindrome
No, the given string is not a palindrome
Yes, the given string is a palindrome
Yes, the given string is a palindrome

Programa Python para verificar se uma determinada string é um palíndromo ou não

Abaixo está a implementação do Python para determinar se a string fornecida é um palíndromo ou não:

# Function to check string palindrome
def checkPalindrome(str):
# Flag to check if the given string is a palindrome
flag = True
# Finding the length of the string
n = len(str)
# Converting the string to lowercase
str = str.lower()
# Initializing low index variable
low = 0
# Initializing high index variable
high = n-1
# Running the loop until high is greater than low
while high > low:
# If the characters are not same, set the flag to false
# and break from the loop
if str[high] != str[low]:
flag = False
break
# Increment the low index variable
low = low + 1
# Decrement the high index variable
high = high - 1
# Check if flag is true or false
if flag:
print('Yes, the given string is a palindrome')
else:
print('No, the given string is not a palindrome')
# Test case: 1
str1 = 'MUO'
checkPalindrome(str1)
# Test case: 2
str2 = 'madam'
checkPalindrome(str2)
# Test case: 3
str3 = 'MAKEUSEOF'
checkPalindrome(str3)
# Test case: 4
str4 = 'racecar'
checkPalindrome(str4)
# Test case: 5
str5 = 'mom'
checkPalindrome(str5)

Saída:





No, the given string is not a palindrome
Yes, the given string is a palindrome
No, the given string is not a palindrome
Yes, the given string is a palindrome
Yes, the given string is a palindrome

Programa C para verificar se uma determinada string é um palíndromo ou não

Abaixo está a implementação em C para determinar se a string fornecida é um palíndromo ou não:

// Including libraries
#include
#include
#include
#include
// Function to check string palindrome
void checkPalindrome(char str[])
{
// Flag to check if the given string is a palindrome
bool flag = true;
// Finding the length of the string
int n = strlen(str);
// Converting the string to lowercase
for(int i = 0; i {
str[i] = tolower(str[i]);
}
// Initializing low index variable
int low = 0;
// Initializing high index variable
int high = n-1;
// Running the loop until high is greater than low
while (high > low)
{
// If the characters are not same, set the flag to false
// and break from the loop
if(str[high] != str[low])
{
flag = false;
break;
}
// Increment the low index variable
low++;
// Decrement the high index variable
high--;
}
// Check if flag is true or false
if (flag)
{
printf('Yes, the given string is a palindrome ⁠n');
}
else
{
printf('No, the given string is not a palindrome ⁠n');
}
return;
}
int main()
{
// Test case: 1
char str1[] = 'MUO';
checkPalindrome(str1);
// Test case: 2
char str2[] = 'madam';
checkPalindrome(str2);
// Test case: 3
char str3[] = 'MAKEUSEOF';
checkPalindrome(str3);
// Test case: 4
char str4[] = 'racecar';
checkPalindrome(str4);
// Test case: 5
char str5[] = 'mom';
checkPalindrome(str5);
return 0;
}

Saída:





como resgatar um vale-presente roblox
No, the given string is not a palindrome
Yes, the given string is a palindrome
No, the given string is not a palindrome
Yes, the given string is a palindrome
Yes, the given string is a palindrome

Programa JavaScript para verificar se uma determinada string é um palíndromo ou não

Abaixo está a implementação de JavaScript para determinar se a string fornecida é um palíndromo ou não:

// Function to check string palindrome
function checkPalindrome(str) {
// Flag to check if the given string is a palindrome
var flag = true;
// Finding the length of the string
var n = str.length;
// Converting the string to lowercase
str = str.toLowerCase();
// Initializing low index variable
var low = 0;
// Initializing high index variable
var high = n-1;
// Running the loop until high is greater than low
while (high > low) {
// If the characters are not same, set the flag to false
// and break from the loop
if(str[high] != str[low]) {
flag = false;
break;
}
// Increment the low index variable
low++;
// Decrement the high index variable
high--;
}
// Check if flag is true or false
if (flag) {
console.log('Yes, the given string is a palindrome');
} else {
console.log('No, the given string is not a palindrome');
}
}
// Test case: 1
var str1 = 'MUO';
checkPalindrome(str1);
// Test case: 2
var str2 = 'madam';
checkPalindrome(str2);
// Test case: 3
var str3 = 'MAKEUSEOF';
checkPalindrome(str3);
// Test case: 4
var str4 = 'racecar';
checkPalindrome(str4);
// Test case: 5
var str5 = 'mom';
checkPalindrome(str5);

Saída:

No, the given string is not a palindrome
Yes, the given string is a palindrome
No, the given string is not a palindrome
Yes, the given string is a palindrome
Yes, the given string is a palindrome

Aprenda a lidar com strings na programação

Trabalhar com strings é parte integrante da programação. Você deve saber como usar e manipular strings em qualquer uma das linguagens de programação como Python, JavaScript, C ++, etc.

Se você está procurando uma linguagem para começar, Python é uma excelente escolha.

Compartilhado Compartilhado Tweet O email Aprendendo Python? Veja como manipular strings

Usar e manipular strings em Python pode parecer difícil, mas é enganosamente simples.

Leia a seguir
Tópicos relacionados
  • Programação
  • Tutoriais de codificação
Sobre o autor Yuvraj Chandra(60 artigos publicados)

Yuvraj é estudante de graduação em Ciência da Computação na Universidade de Delhi, na Índia. Ele é apaixonado por Full Stack Web Development. Quando não está escrevendo, ele está explorando a profundidade de diferentes tecnologias.

Mais de Yuvraj Chandra

Assine a nossa newsletter

Junte-se ao nosso boletim informativo para dicas de tecnologia, análises, e-books grátis e ofertas exclusivas!

Clique aqui para se inscrever