코딩 테스트/99클럽
[99클럽] 코테 스터디 29일차 TIL - 문자열(1528. Shuffle String)
토자맨
2024. 6. 18. 23:32
문제
문제 설명
- 입력값
- 문자열 s
- s의 index값인 indices[]
- 문제 설명
indices[]의 index값을 참조하여 s를 재조립하라
예시
- Example 1:
Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3]
Output: "leetcode"
Explanation: As shown, "codeleet" becomes "leetcode" after shuffling. - Example 2:
Input: s = "abc", indices = [0,1,2]
Output: "abc"
Explanation: After shuffling, each character remains in its position.
제약 조건
- s.length == indices.length == n
- 1 <= n <= 100
- s consists of only lowercase English letters.
- 0 <= indices[i] < n
- All values of indices are unique.
풀이 방법
- 올바른 순서의 문자열을 담기 위한 char[] 배열을 선언한다.
- 문자열 s를 순회하며 문자열 재배치
각 순서의 문자를 charAt(i)로 가져온다.
가져온 문자를 indices[]에 지정된 index값으로 재배치한다. - 재배치 된 char 배열 charr를 String으로 변환하여 return한다.
코드
class Solution {
public String restoreString(String s, int[] indices) {
char[] charr = new char[s.length()];
for (int i = 0; i < s.length(); i++) {
charr[indices[i]] = s.charAt(i);
}
return new String(charr);
}
}
StringBuilder를 이용한 풀이도 있지만 내 풀이가 더 적합하기 때문에 적지 않음
오늘 회고
바로 풀이 방법을 떠올릴 수 있었지만 charAt() 메소드와 반환할 때 return new String(charr)로 하는 것이 바로 떠오르지 않아서 찾아봤다.
오늘도 고생했고 내일도 최선을 다해 살자.