解题思路

这是一个字符串处理问题,需要处理英文缩写。规则如下:

  1. 输入字符串只包含小写字母和空格
  2. 每个单词取首字母组成缩写
  3. 单词之间用空格分隔

解题步骤:

  1. 第一个字母一定是缩写的一部分
  2. 遍历字符串,每当遇到空格后的第一个字母,将其加入缩写中
  3. 注意处理连续空格的情况

代码

#include <iostream>
#include <string>
using namespace std;

string getAbbreviation(string s) {
    string result;
    result += s[0];  // 第一个字母一定是缩写的一部分
    
    for (int i = 1; i < s.length(); i++) {
        if (s[i-1] == ' ' && s[i] >= 'a' && s[i] <= 'z') {
            result += s[i];
        }
    }
    
    return result;
}

int main() {
    string s;
    getline(cin, s);
    cout << getAbbreviation(s) << endl;
    return 0;
}
import java.util.Scanner;

public class Main {
    public static String getAbbreviation(String s) {
        StringBuilder result = new StringBuilder();
        result.append(s.charAt(0));  // 第一个字母一定是缩写的一部分
        
        for (int i = 1; i < s.length(); i++) {
            if (s.charAt(i-1) == ' ' && Character.isLowerCase(s.charAt(i))) {
                result.append(s.charAt(i));
            }
        }
        
        return result.toString();
    }
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        System.out.println(getAbbreviation(s));
        sc.close();
    }
}
def get_abbreviation(s: str) -> str:
    result = s[0]  # 第一个字母一定是缩写的一部分
    
    for i in range(1, len(s)):
        if s[i-1] == ' ' and s[i].islower():
            result += s[i]
            
    return result

# 读取输入
s = input()
print(get_abbreviation(s))

算法及复杂度

  • 算法:字符串遍历
  • 时间复杂度:,其中 为字符串长度
  • 空间复杂度:,其中 为缩写的长度,最坏情况下 (当每个字母后面都跟着一个空格时)