簡單題(需要注意一個細節) 之 hdu 4847 Wow! Such Doge!

//  [7/25/2014 Sjm]
/*
好幾次 Runtime Error(ACCESS_VIOLATION)。。。後來發現:
當有符號數和無符號數出現在同一個表達式中,默認狀態下(不做強制類型轉換)表達式的值爲將結果轉化爲無符號類型的值。
eg:
int as = 4;
string str = "abc";
cout << str.size() << endl; // 輸出值爲 3
cout << str.size() - as << endl;  // 輸出值非 -1
*/
// 法一:
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <string>
using namespace std;
string str, t_str;
string arr_str[17] =
{ "doge",
"Doge", "dOge", "doGe", "dogE",
"DOge", "DoGe", "DogE", "dOGe", "dOgE", "doGE",
"DOGe", "DOgE", "DoGE", "dOGE",
"DOGE"
};

void myGet(int pos) {
	int lim = pos + 4;
	t_str = "";
	for (int i = pos; i < lim; ++i) {
		t_str += str[i];
	}
}

int main()
{
	//freopen("input.txt", "r", stdin);
	int ans = 0;
	while (getline(cin, str)) {
		if (str.size() < 4) continue;
		// 加上此判斷,防止Runtime Error,或者計算 (str.size() - 4) 時強制類型轉換,即:(int)(str.size()) - 4
		for (int i = 0; i <= (str.size() - 4); ++i) {
			myGet(i);
			for (int j = 0; j < 17; ++j) {
				if (t_str == arr_str[j]) {
					ans++;
					break;
				}
			}
		}
	}
	printf("%d\n", ans);
	return 0;
}


// 法二:
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <string>
using namespace std;
string str, t_str;

int main()
{
	//freopen("input.txt", "r", stdin);
	int ans = 0;
	while (getline(cin, str)) {
		if (str.size() < 4) continue;
		for (int i = 0; i <= (str.size() - 4); ++i) {
			if (
				(str[i] == 'D' || str[i] == 'd') &&
				(str[i + 1] == 'O' || str[i + 1] == 'o') &&
				(str[i + 2] == 'G' || str[i + 2] == 'g') &&
				(str[i + 3] == 'E' || str[i + 3] == 'e')) {
				ans++;
			}
		}
	}
	printf("%d\n", ans);
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章