Como verificar se uma string é simétrica com a programação

Uma corda é considerada simétrica se as duas metades da corda forem iguais. Neste artigo, você aprenderá um algoritmo para determinar se uma determinada string é simétrica ou não. Você também aprenderá como implementar esse algoritmo nas linguagens de programação mais populares, como C ++, Python, C e JavaScript.

Declaração do Problema

Você recebe uma string. Você precisa determinar se a string dada é simétrica ou não.

Exemplo 1 : Seja str = "abab".

O dado é simétrico, pois as duas metades da corda são iguais.

Portanto, a saída é "Sim, a string fornecida é simétrica".

Exemplo 2 : Seja str = "madam".

Se o comprimento da string for ímpar, o caractere do meio da string será ignorado. Portanto, 1ª metade = "ma" e 2ª metade = "am". As duas metades não são iguais.

Portanto, a saída é "Não, a string fornecida não é simétrica".

Exemplo 3 : Seja str = "madma".

1ª metade = "ma" e 2ª metade = "ma". Ambas as metades da corda são iguais.

Portanto, a saída é "Sim, a string fornecida é simétrica".

Algoritmo para determinar se uma determinada string é simétrica ou não

Você pode determinar se uma determinada string é simétrica ou não seguindo a abordagem abaixo:

  1. Encontre o comprimento da corda.
  2. Encontre o midIndex da string.
    • Se o comprimento da string for par, midIndex = length / 2 .
    • Se o comprimento da string for ímpar, midIndex = (length / 2) + 1 . Nesse caso, o caractere do meio da string é ignorado para comparação.
  3. Inicializar duas variáveis de ponteiro Pointer1 e pointer2. O ponteiro1 armazenará o índice do primeiro caractere (0) da string e o ponteiro2 armazenará o índice do caractere do meio (midIndex) da string.
  4. Agora compare os personagens correspondentes de ambas as metades do string usando um loop while. Executar um loop while até Pointer1 <midIndex e pointer2 <ComprimentoCadeia.
  5. Compare os caracteres correspondentes nos índices ponteiro1 e ponteiro2 .
  6. Se algum caractere correspondente for diferente, retorne falso . E se nenhum caractere correspondente for encontrado diferente, retorne verdadeiro .
  7. Além disso, certifique-se de incrementar o valor de ponteiro1 e ponteiro2 em cada iteração.

Programa C ++ para determinar se uma determinada string é simétrica ou não

Abaixo está o programa C ++ para determinar se uma determinada string é simétrica ou não:

 // C++ program to check whether the string is symmetrical or not
#include <iostream>
using namespace std;
// Function to check whether the string is symmetrical or not
bool isSymmetrical(string str)
{
int midIndex;
int length = str.length();
// If the length of string is even
if (length % 2 == 0)
{
midIndex = length/2;
}
// If the length of string is odd
else
{
midIndex = length/2 + 1;
}
int pointer1 = 0;
int pointer2 = midIndex;
while(pointer1<midIndex && pointer2<length)
{
if(str[pointer1] == str[pointer2])
{
pointer1 += 1;
pointer2 += 1;
}
else
{
return false;
}
}
return true;
}
// Driver Code
int main()
{
// Test case: 1
string str1 = "abab";
cout << "String 1: " << str1 << endl;
if (isSymmetrical(str1))
{
cout << "Yes, the given string is symmetrical" << endl;
}
else
{
cout << "No, the given string is not symmetrical" << endl;
}
// Test case: 2
string str2 = "madam";
cout << "String 2: " << str2 << endl;
if (isSymmetrical(str2))
{
cout << "Yes, the given string is symmetrical" << endl;
}
else
{
cout << "No, the given string is not symmetrical" << endl;
}
// Test case: 3
string str3 = "madma";
cout << "String 3: " << str3 << endl;
if (isSymmetrical(str3))
{
cout << "Yes, the given string is symmetrical" << endl;
}
else
{
cout << "No, the given string is not symmetrical" << endl;
}
// Test case: 4
string str4 = "civic";
cout << "String 4: " << str4 << endl;
if (isSymmetrical(str4))
{
cout << "Yes, the given string is symmetrical" << endl;
}
else
{
cout << "No, the given string is not symmetrical" << endl;
}
// Test case: 5
string str5 = "khokho";
cout << "String 5: " << str5 << endl;
if (isSymmetrical(str5))
{
cout << "Yes, the given string is symmetrical" << endl;
}
else
{
cout << "No, the given string is not symmetrical" << endl;
}
return 0;
}

Saída:

 String 1: abab
Yes, the given string is symmetrical
String 2: madam
No, the given string is not symmetrical
String 3: madma
Yes, the given string is symmetrical
String 4: civic
No, the given string is not symmetrical
String 5: khokho
Yes, the given string is symmetrical

Relacionado: Como reverter uma string em C ++, Python e JavaScript

Programa Python para determinar se uma determinada string é simétrica ou não

Abaixo está o programa Python para determinar se uma determinada string é simétrica ou não:

 # Python program to check whether the string is symmetrical or not
# Function to check whether the string is symmetrical or not
def isSymmetrical(str):
midIndex = 0
length = len(str)
if length%2 == 0:
midIndex = length//2
else:
midIndex = length//2 + 1
pointer1 = 0
pointer2 = midIndex
while pointer1<midIndex and pointer2<length:
if (str[pointer1] == str[pointer2]):
pointer1 += 1
pointer2 += 1
else:
return False
return True

# Test case: 1
str1 = "abab"
print("String 1:", str1)
if (isSymmetrical(str1)):
print("Yes, the given string is symmetrical")
else:
print("No, the given string is not symmetrical")
# Test case: 2
str2 = "madam"
print("String 2:", str2)
if (isSymmetrical(str2)):
print("Yes, the given string is symmetrical")
else:
print("No, the given string is not symmetrical")
# Test case: 3
str3 = "madma"
print("String 3:", str3)
if (isSymmetrical(str3)):
print("Yes, the given string is symmetrical")
else:
print("No, the given string is not symmetrical")
# Test case: 4
str4 = "civic"
print("String 4:", str4)
if (isSymmetrical(str4)):
print("Yes, the given string is symmetrical")
else:
print("No, the given string is not symmetrical")
# Test case: 5
str5 = "khokho"
print("String 5:", str5)
if (isSymmetrical(str5)):
print("Yes, the given string is symmetrical")
else:
print("No, the given string is not symmetrical")

Saída:

 String 1: abab
Yes, the given string is symmetrical
String 2: madam
No, the given string is not symmetrical
String 3: madma
Yes, the given string is symmetrical
String 4: civic
No, the given string is not symmetrical
String 5: khokho
Yes, the given string is symmetrical

Relacionado: Aprendendo Python? Veja como manipular strings

Programa JavaScript para determinar se uma determinada string é simétrica ou não

Abaixo está o programa JavaScript para determinar se uma determinada string é simétrica ou não:

 // JavaScript program to check whether the string is symmetrical or not
// Function to check whether the string is symmetrical or not
function isSymmetrical(str) {
var midIndex;
var length = str.length;
// If the length of string is even
if (length % 2 == 0) {
midIndex = Math.floor(length/2);
}
// If the length of string is odd
else {
midIndex = Math.floor(length/2) + 1;
}
var pointer1 = 0;
var pointer2 = midIndex;
while(pointer1<midIndex && pointer2<length) {
if(str[pointer1] == str[pointer2]) {
pointer1 += 1;
pointer2 += 1;
} else {
return false;
}
}
return true;
}

// Test case: 1
var str1 = "abab";
document.write("String 1: " + str1 + "<br>");
if (isSymmetrical(str1)) {
document.write("Yes, the given string is symmetrical" + "<br>");
} else {
document.write("No, the given string is not symmetrical" + "<br>");
}
// Test case: 2
var str2 = "madam";
document.write("String 2: " + str2 + "<br>");
if (isSymmetrical(str2)) {
document.write("Yes, the given string is symmetrical" + "<br>");
} else {
document.write("No, the given string is not symmetrical" + "<br>");
}
// Test case: 3
var str3 = "madma";
document.write("String 3: " + str3 + "<br>");
if (isSymmetrical(str3)) {
document.write("Yes, the given string is symmetrical" + "<br>");
} else {
document.write("No, the given string is not symmetrical" + "<br>");
}
// Test case: 4
var str4 = "civic";
document.write("String 4: " + str4 + "<br>");
if (isSymmetrical(str4)) {
document.write("Yes, the given string is symmetrical" + "<br>");
} else {
document.write("No, the given string is not symmetrical" + "<br>");
}
// Test case: 5
var str5 = "khokho";
document.write("String 5: " + str5 + "<br>");
if (isSymmetrical(str5)) {
document.write("Yes, the given string is symmetrical" + "<br>");
} else {
document.write("No, the given string is not symmetrical" + "<br>");
}

Saída:

 String 1: abab
Yes, the given string is symmetrical
String 2: madam
No, the given string is not symmetrical
String 3: madma
Yes, the given string is symmetrical
String 4: civic
No, the given string is not symmetrical
String 5: khokho
Yes, the given string is symmetrical

Relacionado: Como encontrar o caractere que ocorre com mais frequência em uma string

Resolva problemas com base em strings

Strings são um dos tópicos mais importantes para entrevistas de programação. Você deve resolver alguns dos famosos problemas de programação baseados em strings como verificar se uma string é um palíndromo, verificar se duas strings são anagramas uma da outra, encontrar o caractere que ocorre com mais frequência em uma string, inverter uma string, etc. se você ' procuro estar totalmente preparado.