字符串和声!
[题目链接](https://www.nowcoder.com/practice/b1c6df9ed4b64ba0bfd3763bd0c26157)
思路
给定一个由小写字母和连接线 - 组成的字符串,用竖线 | 划分为若干小节。对于给定的延迟值 ,要求输出该字符串的"和声":对每个小节,在前面插入
个下划线
_,然后截取前 个字符(
为该小节的原始长度)。
关键观察
对于长度为 的小节,插入
个下划线后取前
位,等价于:
- 若
:整个小节全部变成下划线
_; - 若
:前
个字符为下划线,后面紧跟原小节的前
个字符。
注意 可能非常大(达到
),因此不能真的创建长度为
的字符串来拼接,必须根据上述两种情况分别处理。
输入格式处理
输入可能跨多行,每行以 | 开头和结尾。逐行读入,对每行按 | 分割出小节,逐个处理后按相同的行格式输出即可。
复杂度分析
- 时间复杂度:
,其中
为字符串总长度,每个字符恰好被读入和输出各一次。
- 空间复杂度:
,用于存储输入和输出。
代码
#include <iostream>
#include <string>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, k;
cin >> n >> k;
string tmp;
getline(cin, tmp);
string line;
while (getline(cin, line)) {
string out;
out += '|';
string cur;
for (int i = 1; i < (int)line.size(); i++) {
if (line[i] == '|') {
int len = cur.size();
if (k >= len) {
out.append(len, '_');
} else {
out.append(k, '_');
out.append(cur, 0, len - k);
}
out += '|';
cur.clear();
} else {
cur += line[i];
}
}
cout << out << "\n";
}
return 0;
}
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
String firstLine = br.readLine().trim();
String[] parts = firstLine.split(" ");
int n = Integer.parseInt(parts[0]);
int k = Integer.parseInt(parts[1]);
String line;
while ((line = br.readLine()) != null) {
sb.append('|');
StringBuilder cur = new StringBuilder();
for (int i = 1; i < line.length(); i++) {
if (line.charAt(i) == '|') {
int len = cur.length();
if (k >= len) {
for (int j = 0; j < len; j++) sb.append('_');
} else {
for (int j = 0; j < k; j++) sb.append('_');
sb.append(cur, 0, len - k);
}
sb.append('|');
cur.setLength(0);
} else {
cur.append(line.charAt(i));
}
}
sb.append('\n');
}
System.out.print(sb);
}
}

京公网安备 11010502036488号