짬뽕얼큰하게의 맨땅에 헤딩 :: Adding Spaces to a String

Leetcode Problem:

Summary

  • Given a string and a vector of indices where spaces need to be added, insert spaces before the characters at the given indices.

Approach

  • The approach is to iterate over the vector of indices and for each index, insert a space before the character at that index
  • After the loop, add the remaining characters to the string.

Complexity

  • O(n), where n is the number of indices in the vector.

Explanation

  • The code uses a for loop to iterate over the vector of indices
  • For each index, it uses the substr function to get the substring of the original string from the start index to the end index
  • It then appends a space to the result string and updates the start index to the end index
  • After the loop, it uses the substr function again to get the remaining substring of the original string and appends it to the result string
  • The result string is then returned.

Solution Code:


class Solution {
public:
    string addSpaces(string s, vector& spaces) {
        int start = 0;
        int end;
        string ans = "";
        for(int i = 0 ; i < spaces.size(); i++){
            end = spaces[i];
            ans += s.substr(start, end-start);
            ans += " ";
            start = end;
        }
        ans += s.substr(start, s.size()-start);

        return ans;
    }
};
블로그 이미지

짬뽕얼큰하게

,