A1084

本題可以從兩個不同角度思考:
1、我的想法:第二個字符串是按照第一個字符串的順序敲出來的,只不過因爲鍵盤老舊,有些鍵無法輸出,那麼,可以將兩個字符串str1,str2分別從前往後比較,若相等,則各向後移一位;若不等,則str1向後移一位,判斷不相等的這個字符之前是否已經輸出過,若已輸出過,則將其忽略,若沒輸出過,則輸出之。最後,要麼兩個字符串共同遍歷到末尾;要麼str2遍歷到了末尾,str1還剩下幾個無法呈現在str2上的字符,需額外處理之。

#include<cstdio>
#include<cstdlib>
#include<string.h>
#include<iostream>
#include<vector>
#include<set>
#include<map>
#include<string>
#include<algorithm>
using namespace std;
int hashes(char c){
		if(c>='0'&&c<='9')return c-'0';
		else if(c=='_')return 99;
		else if(c>='A'&&c<='Z')return c-'0';
		else if(c>='a'&&c<='z')return c-'0'-32;
	}
int main(){
	#ifdef ONLINE_JUDGE
	#else
		freopen("1.txt","r",stdin);
	#endif
	bool flag[100];                                 //記錄某個特定字符是否已被打印過了 
	string orig,type;
	getline(cin,orig);
	getline(cin,type);
	int i=0,j;
	for(j=0;j<type.length();){                      //一次遍歷 
		if(orig[i]!=type[j]){
			int convert=hashes(orig[i]);
			if(flag[convert]==false){
				if(orig[i]>='a'&&orig[i]<='z'){
					printf("%c",orig[i]-32);
				}else{
					printf("%c",orig[i]);
				}
				flag[convert]=true;
			}
			i++;
		}else{
			i++;
			j++;
		}
	}
	while(i<orig.length()){                               //type遍歷到了末尾,orig還剩下幾個無法呈現在type上的字符,需額外處理之
			int convert=hashes(orig[i]);
			if(flag[convert]==false){
				if(orig[i]>='a'&&orig[i]<='z'){
					printf("%c",orig[i]-32);
				}else{
					printf("%c",orig[i]);
				}
				flag[convert]=true;
			}
			i++;
	}
	return 0;
}

2、算法筆記的思路:因鍵盤老舊無法輸出的字符,在str2中不可能出現,因此,可將str1從頭至尾遍歷,每遍歷一個字符,就將str2遍歷一遍,尋找是否有相等的字符,若沒有,則是我們要找的字符,然後再判斷該字符是否已被輸出過了。

#include<cstdio>
#include<cstdlib>
#include<string.h>
#include<iostream>
#include<vector>
#include<set>
#include<map>
#include<string>
#include<algorithm>
using namespace std;
int main(){
	#ifdef ONLINE_JUDGE
	#else
		freopen("1.txt","r",stdin);
	#endif
	char str1[100],str2[100];
	scanf("%s",str1);
	scanf("%s",str2);
	bool hashTable[128];
	for(int i=0;i<strlen(str1);i++){
		int j;
		char c1,c2;
		c1=str1[i];
		if(c1>='a'&&c1<='z')c1=c1-32;
		for(j=0;j<strlen(str2);j++){
			c2=str2[j];
			if(c2>='a'&&c2<='z')c2=c2-32;
			if(c1==c2)break;
		}
		if(j==strlen(str2)&&hashTable[c1]==false){
			hashTable[c1]=true;
			printf("%c",c1);
		}
	}
	return 0;
}

注:下面代碼與上面的唯一的區別,上面用的字符數組,下面用的字符串,結果下面的通過不了

#include<cstdio>
#include<cstdlib>
#include<string.h>
#include<iostream>
#include<vector>
#include<set>
#include<map>
#include<string>
#include<algorithm>
using namespace std;
int main(){
	#ifdef ONLINE_JUDGE
	#else
		freopen("1.txt","r",stdin);
	#endif
	string str1,str2;
	getline(cin,str1);
	getline(cin,str2);
	bool hashTable[128];
	for(int i=0;i<str1.length();i++){
		int j;
		char c1,c2;
		c1=str1[i];
		if(c1>='a'&&c1<='z')c1=c1-32;
		for(j=0;j<str2.length();j++){
			c2=str2[j];
			if(c2>='a'&&c2<='z')c2=c2-32;
			if(c1==c2)break;
		}
		if(j==str2.length()&&hashTable[c1]==false){
			hashTable[c1]=true;
			printf("%c",c1);
		}
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章