개발 일지
1544. Make The String Great (문자열 다듬기) C# 본문
Given a string s of lower and upper case English letters.
A good string is a string which doesn't have two adjacent characters s[i] and s[i + 1] where:
- 0 <= i <= s.length - 2
- s[i] is a lower-case letter and s[i + 1] is the same letter but in upper-case or vice-versa.
To make the string good, you can choose two adjacent characters that make the string bad and remove them. You can keep doing this until the string becomes good.
Return the string after making it good. The answer is guaranteed to be unique under the given constraints.
Notice that an empty string is also good.
소문자와 대문자로 구성된 문자열 s가 주어집니다.
올바른 문자열은 두 개의 인접한 문자 s[i]와 s[i + 1]가 아래의 경우가 없는 문자열입니다.
- 0 <= i <= s.length - 2
- s[i]는 소문자이고 s[i + 1]은 동일한 문자이지만 대문자이거나 그 반대입니다.
문자열을 올바르게 만들기 위해 문자열이 잘못된 두 개의 인접 문자를 선택하고 제거할 수 있습니다. 문자열이 올바르게 될 때까지 계속 이 작업을 수행하면 됩니다.
문자열을 올바륵 만든 후 반환합니다. 주어진 제약 조건 하에서 답은 고유할 것을 보장합니다.
빈 문자열 또한 올바릅니다.
예시 1:
입력: s = "leEeetcode"
출력: "leetcode"
설명: 첫 번째 단계에서 i = 1 또는 i = 2를 선택하면 "leEetcode"가 "leetcode"로 축소됩니다.
예시 2:
입력: s = "abBAcC"
출력: ""
설명: 가능한 시나리오가 많으며 모두 같은 대답으로 이어집니다. 예를 들어:
"abBAcC" --> "aAcC" --> "cC" --> ""
"abBAcC" --> "abBA" --> "aA" --> ""
예시 3:
예 3:
입력: s = "s"
출력: "s"
조건:
- 1 <= s.length <= 100
- s에는 영문 소문자와 대문자만 포함되어 있습니다.
정답:
public class Solution {
public string MakeGood(string s) {
for(int i = 1; i < s.Length; i++)
{
if(Math.Abs(s[i - 1] - s[i]) == 32)
{
s = s.Substring(0, i - 1) + s.Substring(i + 1);
s = MakeGood(s);
break;
}
}
return s;
}
}
해설: s의 길이만큼 반복문을 돌릴때 i와 i-1의 아스키코드 값을 비교하여 차의 절대값이 32일때 해당 문자를 자른 후 재귀하여 s의 길이까지 모드 체크한 후 그 값을 return해주었습니다.
'코딩 테스트 > LeetCode' 카테고리의 다른 글
387. First Unique Character in a String (문자열의 첫 번째 고유 문자) C# (0) | 2022.11.18 |
---|---|
26. Remove Duplicates from Sorted Array (정렬된 배열에서 중복 제거) C# (0) | 2022.11.16 |
345. Reverse Vowels of a String (문자열의 모음 뒤집기) C# (0) | 2022.11.07 |
766. Toeplitz Matrix (퇴플리츠 행렬) C# (0) | 2022.11.03 |
1108. Defanging an IP Address (IP 주소 훼손하기) C# (0) | 2022.11.01 |