Palindrome Check

Tristan·2024년 7월 24일

A program that receives N string data and outputs YES when reading from the front or from the back (pale string) and outputs NO unless it is a palindromic string is written.

It is not case sensitive when examining a single sentence.

Input:

The integer N (1<=N<=20) is given in the first line, and N words are entered from the next line. The length of each word does not exceed 100.

Output:

Output the result of the string as YES or NO for each line.

Input Example:

5
level
moon
abcba
soon
gooG

Output Example:

#1 YES
#2 NO
#3 YES
#4 NO
#5 YES

Solution

  • set up a for loop that will repeat the process n times
  • two solutions available: slicing and letter check
  • slicing
    • create an if loop that will slice the word ([::-1]), which will check if the word is a palindrome
    • if the word is palindrome, it will return YES
    • if not, it will return NO
  • letter check
    • create a for loop that will go through the length / 2 of the word
      ex) pineapple >> len = 9 >> the for loop will go through until the 4th letter, which is 'e'
    • since palindrome has a same format of word while reading backword, we only need to check until the middle of the word
    • if the jth letter != j-1th letter (last letter of the word), the word is not a palindrome, so we will return NO
    • if the j, j+1...th letters are same with the j-1, j-2...th letters, the word is a palindrome, so we will return YES
n = int(input())

for i in range (n):
    word = input()
    size = len(word)
    
# Slicing

    if word == word[::-1]:
        print ("#%d YES" %(i+1))
    
    else:
        print ("#%d NO" %(i+1))
                
'''
# Letter Check

    for j in range (size // 2):
        if word[j] != word[-1-j]:
            print ("#%d NO" %(i+1))
            break
    
    else:
        print ("#%d YES" %(i+1))
'''
profile
@Columbia

0개의 댓글