`
bcyy
  • 浏览: 1831028 次
文章分类
社区版块
存档分类
最新评论

Codeforces - cAPS lOCK 大小写字母转换问题

 
阅读更多

按如下规则转换字母:

Let's consider that a word has been typed with the Caps lock key accidentally switched on, if:

  • either it only contains uppercase letters;
  • or all letters except for the first one are uppercase.

In this case we should automatically change the case of all letters. For example, the case of the letters that form words "hELLO", "HTTP", "z" should be changed.

单个大写字母是否需要转换?需要。

cBCD -> Cbcd

Good -> Good

H -> h

h -> H

看似乎简单,但是解决这个问题可以,要优雅地写出程序,那么就是不容易的了。

下面看我的程序,使用automata的知识,写个小小的automata系统,优雅地解决这个问题:

#include <iostream>
#include <vector>
#include <string>

using namespace std;

enum CASE
{
	ALL_UPPERS,
	ONLY_FIRST_LOWER,
	CORRECT,
	ILEGAL
};

const static int trans[6][2] = {
	{1,	2},					//0 Init and Invalid
	{3,	5},					//1 first upper
	{4,	5},					//2 first lower
	{3,	5},					//3 all upper
	{4,	5},					//4 first low other upper
	{5,	5}	};				//5 correct words

CASE checkLetters(string &s)
{
	int state = 0;
	for (int i = 0; i < s.size(); i++)
	{
		int input = -1;
		if ('A' <= s[i] && s[i] <= 'Z') input = 0;
		if ('a' <= s[i] && s[i] <= 'z') input = 1;
		if (-1 == input) return ILEGAL;
		state = trans[state][input];
	}
	if (1 == state || 3 == state) return ALL_UPPERS;
	else if (2 == state || 4 == state) return ONLY_FIRST_LOWER;
	return CORRECT;
}

void transAllLowers(string &s)
{
	for (int i = 0; i < s.size(); i++)
	{
		s[i] = s[i] - 'A' + 'a';
	}
}

void transFirstUpper(string &s)
{
	s[0] = s[0] - 'a' + 'A';
	for (int i = 1; i < s.size(); i++)
	{
		s[i] = s[i] - 'A' + 'a';
	}
}

void cAPSLOOCK()
{
	string s;
	cin>>s;	
	CASE C = checkLetters(s);
	if (ALL_UPPERS == C) transAllLowers(s);
	else if (ONLY_FIRST_LOWER == C) transFirstUpper(s);
	else if (ILEGAL == C) cout<<"ILEGAL", exit(0);
	cout<<s;
}

int main()
{
	cAPSLOOCK();
	return 0;
}




分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics