校招算法笔面试 | 校招笔面试真题-字符串替换

题目

题目链接

解题思路

  1. 基本思路:

    • 遍历原字符串寻找"%s"
    • 用参数数组中的字符依次替换
    • 剩余参数添加到末尾
    • 使用StringBuilder提高效率
  2. 关键点:

    • 处理"%s"占位符
    • 维护参数数组的索引
    • 字符串拼接效率

代码

class StringFormat {
public:
    string formatString(string A, int n, vector<char>& arg, int m) {
        string result;
        int argIndex = 0;
        
        for(int i = 0; i < n; i++) {
            if(i < n-1 && A[i] == '%' && A[i+1] == 's') {
                // 替换占位符
                if(argIndex < m) {
                    result += arg[argIndex++];
                }
                i++; // 跳过's'
            } else {
                result += A[i];
            }
        }
        
        // 添加剩余参数
        while(argIndex < m) {
            result += arg[argIndex++];
        }
        
        return result;
    }
};
public class StringFormat {
    public String formatString(String A, int n, char[] arg, int m) {
        StringBuilder result = new StringBuilder();
        int argIndex = 0;
        
        for(int i = 0; i < n; i++) {
            if(i < n-1 && A.charAt(i) == '%' && A.charAt(i+1) == 's') {
                // 替换占位符
                if(argIndex < m) {
                    result.append(arg[argIndex++]);
                }
                i++; // 跳过's'
            } else {
                result.append(A.charAt(i));
            }
        }
        
        // 添加剩余参数
        while(argIndex < m) {
            result.append(arg[argIndex++]);
        }
        
        return result.toString();
    }
}
class StringFormat:
    def formatString(self, A, n, arg, m):
        result = []
        arg_index = 0
        i = 0
        
        while i < n:
            if i < n-1 and A[i] == '%' and A[i+1] == 's':
                # Replace placeholder
                if arg_index < m:
                    result.append(arg[arg_index])
                    arg_index += 1
                i += 2  # Skip 's'
            else:
                result.append(A[i])
                i += 1
        
        # Add remaining arguments
        while arg_index < m:
            result.append(arg[arg_index])
            arg_index += 1
        
        return ''.join(result)

算法及复杂度

  • 算法:字符串遍历替换
  • 时间复杂度: O ( n ) \mathcal{O}(n) O(n),其中 n n n 为字符串长度
  • 空间复杂度: O ( n ) \mathcal{O}(n) O(n),用于存储结果字符串
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值