马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
学习记载
2025.3.30
标题:
思绪:
遍历。
解题步调:
1.初始化 StringBuilder:创建一个 StringBuilder 对象 ans,用于构建效果字符串。
初始容量设为 s.length() + spaces.length,由于终极字符串的长度是原字符串长度加上插入的空格数(每个空格占一个字符)。
2.遍历字符串并插入空格:利用变量 j 跟踪当前须要处理处罚的下一个空格位置(即 spaces 数组的索引)。遍历字符串 s 的每个字符(索引 i):如果 j 未越界且当前字符的索引 i 便是 spaces[j],则在 ans 中插入一个空格,并递增 j。将当前字符 s.charAt(i) 追加到 ans 中。
3.返回效果:将 StringBuilder 转换为字符串并返回。
代码:
- char * addSpaces(char * s, int* spaces, int spacesSize){
- char *res = (char *)malloc(strlen(s) + 1 + spacesSize);
- char *pc = res;
- int lastpos = 0;
- for (int i = 0; i < spacesSize; i++) {
- int len = spaces[i] - lastpos;
- lastpos = spaces[i];
- memcpy(pc, s, len);
- pc += len;
- s += len;
- *pc = ' ';
- pc++;
- }
- memcpy(pc, s ,strlen(s) + 1);
- return res;
- }
复制代码- class Solution {
- public String addSpaces(String s, int[] spaces) {
- StringBuilder ans = new StringBuilder(s.length() + spaces.length);
- int j = 0;
- for (int i = 0; i < s.length(); i++) {
- if (j < spaces.length && spaces[j] == i) {
- ans.append(' ');
- j++;
- }
- ans.append(s.charAt(i));
- }
- return ans.toString();
- }
- }
复制代码 复杂度:
O(N)
O(N)
|