题意

给出 个只包含小写字母的字符串,将其中长度为奇数的字符串按顺序拼接后输出。

思路

纯模拟题,没有任何弯弯绕绕。

逐个读入字符串,判断长度是否为奇数(len % 2 == 1),如果是就拼接到结果串的末尾。最后输出即可。

唯一需要注意的点:字符串总长度可能很大(题目说总和不超过某个值),所以拼接时用 StringBuilder(Java)或直接 +=(C++ 的 string)即可,不需要额外优化。

代码

#include <bits/stdc++.h>
using namespace std;
int main(){
    int n;
    scanf("%d", &n);
    string res;
    for(int i = 0; i < n; i++){
        char s[100001];
        scanf("%s", s);
        int len = strlen(s);
        if(len % 2 == 1) res += s;
    }
    printf("%s\n", res.c_str());
    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));
        int n = Integer.parseInt(br.readLine().trim());
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n; i++) {
            String s = br.readLine().trim();
            if (s.length() % 2 == 1) sb.append(s);
        }
        System.out.println(sb.toString());
    }
}

复杂度

  • 时间复杂度:,其中 为所有字符串的总长度。
  • 空间复杂度:,存储结果字符串。