2011年11月NOKIA笔试题目第一题
1. 输入: char *S
字符串S是a-z的任意字符组成的乱序字符串,没有任何规律。
要求判断经过顺序调整,字符串S可否变成回文数。
输出:
可变为回文数输出为1,不能变成输出为0.
例如:
wjockwajiaock可变为回文数
wojackikcajow ,返回1.
abcbba,不能变为回文数,返回0.
---------------------------------------------------
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int IsExist(vector<char> c, char s)
{
if (c.size() == 0)
return -1;
for (int i = 0; i < c.size(); i++)
{
if (c[i] == s)
return i;
}
return -1;
}
bool SN(const char *s)
{
string st(s);
int n = st.length();
vector<char> c;
vector<int> q;
for (int i = 0; i < n; i++)
{
int index = IsExist(c, st[i]);
if (index > -1)
q[index]++;
else
{
c.push_back(st[i]);
q[c.size() - 1] = 1;
}
}
if (n % 2 == 0)
{
for (int i = 0; i < q.size(); i++)
{
if (q[i] % 2 != 0)
return 0;
}
return 1;
}
else
{
int temp = 0;
for (int i = 0; i < q.size(); i++)
{
if (q[i] % 2 != 0)
temp++;
}
if (temp == 1)
return 1;
else
return 0;
}
}
int main()
{
cout << "input a string : " << endl;
string t;
cin >> t;
const char* s = t.c_str();
cout << SN(s) << endl;
system("pause");
}
有错误,但是不知道怎么改,希望大侠们能帮忙。。
[解决办法]
- C/C++ code
#include <iostream>#include <string>#include <vector>using namespace std;int IsExist(vector<char> c, char s){ if (c.size() == 0) return -1; for (int i = 0; i < c.size(); i++) { if (c[i] == s) return i; } return -1;}bool SN(const char *s){ string st(s); int n = st.length(); vector<char> c; vector<int> q; for (int i = 0; i < n; i++) { int index = IsExist(c, st[i]); if (index > -1) q[index]++; else { c.push_back(st[i]); q.push_back(1);//这儿改成这样子 } } if (n % 2 == 0) { for (int i = 0; i < q.size(); i++) { if (q[i] % 2 != 0) return 0; } return 1; } else { int temp = 0; for (int i = 0; i < q.size(); i++) { if (q[i] % 2 != 0) temp++; } if (temp == 1) return 1; else return 0; }}int main(){ cout << "input a string : " << endl; string t; cin >> t; const char* s = t.c_str(); cout << SN(s) << endl; system("pause");}
[解决办法]
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int IsExist(vector<char> c, char s) //判断是否有重复的字符
{
if (c.size() == 0)
return -1;
for (int i = 0; i < c.size(); i++)
{
if (c[i] == s)
return i;
}
return -1;
}
bool SN(const char *s)//判断是否为回文数
{
string st(s);
int n = st.length();
vector<char> c; //存储没有重复的字符
vector<int> q; //记录重复字符
for (int i = 0; i < n; i++)
{
int index = IsExist(c, st[i]);
if (index > -1)
q[index]++;
else
{
c.push_back(st[i]);
q.push_back(1);//这儿改成这样子 (没有重复则表示只有一个)
}
}
if (n % 2 == 0)//输入的字符为偶数个(重复字符必须为偶数个才是回文数)
{
for (int i = 0; i < q.size(); i++)
{
if (q[i] % 2 != 0)
return 0;
}
return 1;
}
else //输入的字符为奇数个(只有一个重复字符为奇数个才是回文数)
{
int temp = 0;
for (int i = 0; i < q.size(); i++)
{
if (q[i] % 2 != 0)
temp++;
}
if (temp == 1)
return 1;
else
return 0;
}
}
int main()
{
cout << "input a string : " << endl;
string t;
cin >> t;
const char* s = t.c_str();
cout << SN(s) << endl;
system("pause");
return 0;
}
略作注示为来者