首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

九度 OJ 1049:字符串刪除指定字符

     編輯:關於C++

問題描述

輸入字符串 s 和字符 c,刪除 s 中所有字符 c,輸出結果。多組測試數據。

解法一:直接遍歷輸出

讀取字符串和字符,遍歷字符串,遇到非 c 字符直接輸出。

#include 
#include 
using namespace std;
int main() {
    string s;
    while (cin >> s) {
        char c; cin >> c;
        for (char ch : s) if (ch != c) cout << ch;
        cout << endl;
    }
    return 0;
}

解法二:使用 erase-remove 惯用法

利用標準庫算法 remove 將目標字符移至末尾,再 erase 刪除。

#include 
#include 
#include 
using namespace std;
int main() {
    string s, cstr;
    while (cin >> s >> cstr) {
        char c = cstr[0];
        s.erase(remove(s.begin(), s.end(), c), s.end());
        cout << s << endl;
    }
    return 0;
}

複雜度分析

  • 時間複雜度:O(n) 每字符串。
  • 空間複雜度:O(1) 額外空間(原地修改)。

總結

簡單的字符串處理題,考察基本輸入輸出與字符過濾。C++ STL 的 remove-erase 惯用法代碼簡潔高效。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved