Here's a solution to convert the given string `S` into a palindrome by replacing question marks with lowercase letters, or returning "NO" if it's not possible:
```python
def solution(S):
S = list(S) # Convert string to list for mutability
N = len(S)
for i in range((N + 1) // 2):
left, right = S[i], S[N - 1 - i]
if left == '?' and right == '?':
S[i] = S[N - 1 - i] = 'a' # Replace both '?' with 'a'
elif left == '?':
S[i] = right # Replace '?' on the left with the right character
elif right == '?':
S[N - 1 - i] = left # Replace '?' on the right with the left character
elif left != right:
return "NO" # If characters do not match and are not '?', it's impossible
return ''.join(S) # Convert list back to string and return
# Examples
print(solution("?ab??a")) # Output: "aabbaa"
print(solution("bab??a")) # Output: "NO"
print(solution("?a?")) # Output: "aaa" or "aza"
```
### Explanation:
1. **Convert the String to a List**: This makes the string mutable, allowing for in-place modifications.
2. **Iterate Over the First Half of the String**: Since a palindrome reads the same forward and backward, you only need to check and modify the first half.
3. **Replace Question Marks**:
- If both characters at positions `i` and `N-1-i` are '?', replace both with 'a'.
- If only one character is '?', replace it with the corresponding character from the other half.
- If both characters are not '?', check if they are equal; if not, return "NO".
4. **Convert Back to String and Return**: After processing, convert the list back to a string.
This approach ensures correctness by handling all possible cases where question marks need to be replaced to form a palindrome. If it detects any impossible condition, it promptly returns "NO".
'대기업 일상' 카테고리의 다른 글
코딩 삼성sw아카데미 개발자 연봉 파이썬 코딩공부 (0) | 2024.08.28 |
---|---|
유튜브나 다른 매체에서 나오는 의견들은 일반적으로 흥미를 끌기 위해 과장 (0) | 2024.08.28 |
이해하기 어렵고 복잡한 상황이네요. 아버지께서 자신의 가족을 돕고자 (0) | 2024.08.27 |
이해하기 어렵고 복잡한 상황이네요. 아버지께서 자신의 가족을 돕고자 (0) | 2024.08.27 |
이해하기 어렵고 복잡한 상황이네요. 아버지께서 자신의 가족을 돕고자 (0) | 2024.08.27 |
댓글