# String Manipulation# Substitution# Character Mapping

e578 - 10222 - Decode the Mad man

🔗 前往 ZeroJudge 原題

題目描述

題目要求將輸入字串中的每個字符替換為鍵盤上其左邊第二個字符。空白和換行符號保持不變,反斜線替換為左方括號。

解題思路

題目描述的替換規則非常直接。程式碼中定義了四個字串 one, q, a, z 分別對應鍵盤上數字、qwerty、asdfgh、zxcvb 區域的字符。程式遍歷輸入字串,對於每個字符,檢查它是否在上述四個字串中,如果在,則輸出其左邊第二個字符。對於空白字符和反斜線,則按照題目要求進行處理。

複雜度分析

  • 時間複雜度: O(n*m),其中 n 是輸入字串的長度,m 是鍵盤區域字串的最大長度 (one, q, a, z)。因為對於輸入字串的每個字符,都需要遍歷四個鍵盤區域字串。
  • 空間複雜度: O(1),程式使用的額外空間是常數級別,主要用於儲存鍵盤區域字串和臨時變數。

程式碼

#include <iostream>
#include <string>
using namespace std;
int main(){
	string one="`1234567890-=";
	string q="qwertyuiop[]";
	string a="asdfghjkl;'";
	string z="zxcvbnm,./";
	string x;
	while(getline(cin,x)){
		for(int i=0;i<x.length();i++){
			for(int j=0;j<one.length();j++){
				if(x[i]==one[j]){
					cout << one[j-2];
				}
			}
			for(int j=0;j<q.length();j++){
				if(x[i]==q[j]){
					cout << q[j-2];
				}
			}
			for(int j=0;j<a.length();j++){
				if(x[i]==a[j]){
					cout << a[j-2];
				}
			}
			for(int j=0;j<z.length();j++){
				if(x[i]==z[j]){
					cout << z[j-2];
				}
			}
			if(x[i]==' '){
				cout << ' ';
			}
			if(x[i]=='\\'){
				cout << '[';
			}
		}
		cout << endl;
	}
}

Discussion