Проверить, совпадает ли данная строка с ее отражением в зеркале
Дана строка S, содержащая только символы английского алфавита в верхнем регистре. Задача состоит в том, чтобы выяснить, совпадает ли S со своим отражением в зеркале.
Примеры:
Ввод: str = "AMA" Выход: ДА АМА - это то же самое, что и отражение в зеркале. Ввод: str = "ZXZ" Выход: НЕТ
Подход: очевидно, что строка должна быть палиндромом, но этого недостаточно. Все символы в строке должны быть симметричными, чтобы их отражение было одинаковым. Симметричные символы - AHIMOTUVWXY .
- Сохраните симметричные символы в unordered_set.
- Пройдите по строке и проверьте, присутствует ли в строке какой-либо несимметричный символ. Если да, то верните false.
- В противном случае проверьте, является ли строка палиндромом или нет. Если строка также является палиндромом, верните true, иначе верните false.
Below is the implementation of the above approach:
C++
// C++ implementation of the// above approach#include <bits/stdc++.h>using namespace std;// Function to check reflectionbool isReflectionEqual(string s){ // Symmetric characters unordered_set<char> symmetric = { "A", "H", "I", "M", "O", "T", "U", "V", "W", "X", "Y" }; int n = s.length(); for (int i = 0; i < n; i++) // If any non-symmetric character is // present, the answer is NO if (symmetric.find(s[i]) == symmetric.end()) return false; string rev = s; reverse(rev.begin(), rev.end()); // Check if the string is a palindrome if (rev == s) return true; else return false;}// Driver codeint main(){ string s = "MYTYM"; if (isReflectionEqual(s)) cout << "YES"; else cout << "NO";} |
Java
// Java implementation of above approachimport java.util.*;class GFG{ static String Reverse(String s) { char[] charArray = s.toCharArray(); reverse(charArray, 0, charArray.length - 1); return new String(charArray); } // Function to check reflection static boolean isReflectionEqual(String s) { HashSet<Character> symmetric = new HashSet<>(); // Symmetric characters symmetric.add("A"); symmetric.add("H"); symmetric.add("I"); symmetric.add("M"); symmetric.add("O"); symmetric.add("T"); symmetric.add("U"); symmetric.add("V"); symmetric.add("W"); symmetric.add("X"); symmetric.add("Y"); int n = s.length(); // If any non-symmetric character is for (int i = 0; i < n; i++) // present, the answer is NO { if (symmetric.contains(s.charAt(i)) == false) { return false; } } String rev = s; s = Reverse(s); // Check if the String is a palindrome if (rev.equals(s)) { return true; } else { return false; } } // Reverse the letters of the word static void reverse(char str[], int start, int end) { // Temporary variable to store character char temp; while (start <= end) { // Swapping the first and last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; } } // Driver code public static void main(String[] args) { String s = "MYTYM"; if (isReflectionEqual(s)) { System.out.println("YES"); } else { System.out.println("NO"); } }}// This code contributed by Rajput-Ji |
Python3
# Python3 implementation of the# above approach# Function to check reflectiondef isReflectionEqual(s): # Symmetric characters symmetric = dict() str1 = "AHIMOTUVWXY" for i in str1: symmetric[i] = 1 n = len(s) for i in range(n): # If any non-symmetric character # is present, the answer is NO if (symmetric[s[i]] == 0): return False rev = s[::-1] # Check if the is a palindrome if (rev == s): return True else: return False# Driver Codes = "MYTYM"if (isReflectionEqual(s)): print("YES")else: print("NO")# This code is contributed by Mohit Kumar |
C#
// C# implementation of the above approachusing System;using System.Collections.Generic ;class GFG{ static string Reverse( string s ) { char[] charArray = s.ToCharArray(); Array.Reverse( charArray ); return new string( charArray ); } // Function to check reflection static bool isReflectionEqual(string s) { HashSet<char> symmetric = new HashSet<char>(); // Symmetric characters symmetric.Add("A"); symmetric.Add("H"); symmetric.Add("I"); symmetric.Add("M"); symmetric.Add("O"); symmetric.Add("T"); symmetric.Add("U"); symmetric.Add("V"); symmetric.Add("W"); symmetric.Add("X"); symmetric.Add("Y"); int n = s.Length; for (int i = 0; i < n; i++) // If any non-symmetric character is // present, the answer is NO if (symmetric.Contains(s[i]) == false) return false; string rev = s; s = Reverse(s); // Check if the string is a palindrome if (rev == s) return true; else return false; } // Driver code static public void Main() { string s = "MYTYM"; if (isReflectionEqual(s)) Console.WriteLine("YES"); else Console.WriteLine("NO"); }}// This code is contributed by Ryuga |
Javascript
<script>// JavaScript implementation of above approach function Reverse(s) { let charArray = s.split(""); reverse(charArray, 0, charArray.length - 1); return charArray.join(""); } // Function to check reflection function isReflectionEqual(s) { let symmetric = new Set(); // Symmetric characters symmetric.add("A"); symmetric.add("H"); symmetric.add("I"); symmetric.add("M"); symmetric.add("O"); symmetric.add("T"); symmetric.add("U"); symmetric.add("V"); symmetric.add("W"); symmetric.add("X"); symmetric.add("Y"); let n = s.length; // If any non-symmetric character is for (let i = 0; i < n; i++) // present, the answer is NO { if (symmetric.has(s[i]) == false) { return false; } } let rev = s; s = Reverse(s); // Check if the String is a palindrome if (rev==(s)) { return true; } else { return false; } } // Reverse the letters of the word function reverse(str,start,end) { // Temporary variable to store character let temp; while (start <= end) { // Swapping the first and last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; } } // Driver code let s = "MYTYM"; if (isReflectionEqual(s)) { document.write("YES"); } else { document.write("NO"); } // This code is contributed by unknown2108</script> |
YES
Сложность времени: O (N)
Вниманию читателя! Не прекращайте учиться сейчас. Освойте все важные концепции DSA с помощью самостоятельного курса DSA по приемлемой для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .
Если вы хотите посещать живые занятия с отраслевыми экспертами, пожалуйста, обращайтесь к Geeks Classes Live и Geeks Classes Live USA.