# String# Conditional Statements

a466 - 12289 - One-Two-Three

🔗 前往 ZeroJudge 原題

題目描述

題目要求辨識包含最多一個錯誤字母的英文單字 "one", "two", 或 "three" 的數值表示 (1, 2, 或 3)。輸入包含多個單字,對於每個單字,輸出其對應的數值。

解題思路

由於題目限制單字長度正確且最多一個錯誤字母,因此可以針對 "one", "two", "three" 的所有可能錯誤情況進行判斷。程式碼通過檢查單字的前幾個字母,以及特定位置的字母是否匹配,來確定單字代表的數值。對於長度為 5 的單字,直接判斷為 '3'。對於其他單字,通過檢查 'o' 和 'n'、'e' 的位置關係,以及 't' 和 'w'、'o' 的位置關係,來判斷是 '1' 還是 '2'。

複雜度分析

  • 時間複雜度: O(n*m),其中 n 是單字數量,m 是單字的最大長度 (在本題中 m=5)。
  • 空間複雜度: O(1),程式碼只使用了常數級別的額外空間。

程式碼

#include <iostream> 
#include <string>

using namespace std;

int main(){
	
	int n=0;
	string a;
	while(cin >> n){
		for(int i=1;i<=n;i++){
			cin >> a;
			if(a.length()==5){
				cout << '3' << endl;
			} 
			else if(a[0]=='o'&&a[1]=='n'){
				cout << '1' << endl;
			}
			else if(a[0]=='o'&&a[2]=='e'){
				cout << '1' << endl;
			}
			else if(a[1]=='n'&&a[2]=='e'){
				cout << '1' << endl;
			}
			else if(a[0]=='t'&&a[1]=='w'){
				cout << '2' << endl;
			}
			else if(a[0]=='t'&&a[2]=='o'){
				cout << '2' << endl;
			}
			else if(a[1]=='w'&&a[2]=='o'){
				cout << '2' << endl;
			}
		} 
	}
	
}

Discussion