Notice
Recent Posts
Recent Comments
Link
«   2025/06   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

hwooo

LeetCode (C/C++, Java) 2109. Adding Spaces to a String 본문

Study/Algorithm

LeetCode (C/C++, Java) 2109. Adding Spaces to a String

hwooo 2024. 12. 5. 00:38

https://leetcode.com/problems/adding-spaces-to-a-string/description


풀이

주어진 배열을 탐색하며 spaces의 사이에 있는 값을 string에 저장하고, spaces에 저장된 인덱스라면 해당 구간에 공백을 채워 넣는다


C/C++ 코드

class Solution {
public:
    string addSpaces(string s, vector<int>& spaces) {
        int size = s.size() + spaces.size();
        string ans;

        int i = 0;
        for (i = 0; i < spaces.size(); i++) {
            if (i == 0)
                ans.append(s.substr(0, spaces[0]));
            else
                ans.append(s.substr(spaces[i - 1], spaces[i] - spaces[i - 1]));
            ans.append(" ");
        }
        ans.append(s.substr(spaces[i - 1]));

        return ans;
    }
};

 

Java 코드

class Solution {
    public String addSpaces(String s, int[] spaces) {
        char[] ans = new char[s.length() + spaces.length];

        int idx = 0, spaceIdx = 0;
        for (int i = 0; i < s.length(); i++) {
            if (spaceIdx < spaces.length && i == spaces[spaceIdx]) {
                ans[idx++] = ' ';
                spaceIdx++;
            }
            ans[idx++] = s.charAt(i);
        }
        return new String(ans);
    }
}