# String Manipulation# Greedy# Character Replacement

c007 - 00272 - TeX Quotes

🔗 前往 ZeroJudge 原題

題目描述

題目要求將輸入字串中的雙引號 " 替換為 TeX 格式的引號,即第一個雙引號替換為 ``,第二個替換為 '',以此類推。輸入為多行字串,直到 EOF 為止。

解題思路

這題的核心在於追蹤目前是否在引號內部。使用一個布林變數 b 來表示目前是否在引號內部。如果遇到雙引號且 btrue (不在引號內部),則輸出 `` 並將 b 設為 false (進入引號內部)。如果遇到雙引號且 bfalse (在引號內部),則輸出 '' 並將 b 設為 true (離開引號內部)。其他字元則直接輸出。

複雜度分析

  • 時間複雜度: O(n),其中 n 是輸入字串的總長度。因為需要遍歷輸入字串一次。
  • 空間複雜度: O(1),因為只使用了常數額外的空間。

程式碼

#include <iostream>
#include <string>

using namespace std;

int main(){
	string a;
	bool b=true; 
	while(getline(cin,a)){
		for(int i=0;i<a.length();i++){
			if(a[i]==34&&b==true){
				cout << "``";
				b=false;
			}
			else if(a[i]==34&&b==false){
				cout << "''";
				b=true;
			}
			else{
				cout << a[i];
			}
		}
		cout << endl;
	}
}

Discussion