Problem
You are given a word S composed only of lowercase letters. For each letter of the alphabet, output the position of its first occurrence in the word if it is present; if it is not present, output -1.
Input
The first line contains the word S. The length of the word does not exceed 100, and it consists only of lowercase letters.
baekjoon
Output
For each letter of the alphabet, output the position of its first occurrence, separated by spaces (e.g., the position of 'a', the position of 'b', ..., the position of 'z'). If a letter is not present in the word, output -1. The first character of the word is at position 0, and the second character is at position 1.
1 0 -1 -1 2 -1 -1 -1 -1 4 3 -1 -1 7 5 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
My first solution
Read the word S from the first line and create an empty str called result. Use a for loop with the Unicode values of lowercase letters to find the index using the find method in S and add the result to result. Finally, use the join method to insert spaces between the characters.
import sys
S = sys.stdin.readline().strip()
result = ""
for i in range(ord('a'), ord('z') + 1):
temp = S.find(chr(i))
result += str(temp)
print(' '.join(result).strip())
1 0 - 1 - 1 2 - 1 - 1 - 1 - 1 4 3 - 1 - 1 7 5 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1
My final solution
I simply thought I could store the indices as strings because the find method returns an index. However, since the find method returns "-1" when the substring is not found, I need to store the results in a list instead. This way, the join method will work as intended.
import sys
S = sys.stdin.readline().strip()
result = []
for i in range(ord('a'), ord('z') + 1):
temp = S.find(chr(i))
result.append(str(temp))
print(' '.join(result))
1 0 -1 -1 2 -1 -1 -1 -1 4 3 -1 -1 7 5 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
'Insights' 카테고리의 다른 글
BOJ Problem 11718: No input values, and No EOFError? (0) | 2024.11.22 |
---|---|
BOJ Problem 2675: Analyzing Escape Character with a Debugger (1) | 2024.11.15 |
BOJ Problem 3052: Is "{}" a set or a dict? (3) | 2024.11.01 |
Committing to GitHub using VS Code: user.name, user.email (3) | 2024.10.25 |