1、首尾字符不变,中间字符降序排列(字符串长度为7)
input :CEAedca
output:CedcEAa
时间空间都没要求。
void solution1()
{
char str[8];
cin >> str;
for (int i = 1; i < 6; i++)
{
bool isChange = false;
for (int j = 1; j < 6 - i; j++)
{
if (str[j] < str[j + 1])
{
isChange = true;
char t = str[j];
str[j] = str[j + 1];
str[j + 1] = t;
}
}
if (!isChange)
break;
}
cout << str;
}
2、一串数字10个,按照顺序,奇数位填充奇数,偶数位填充偶数,没有数字填充0
input :53, 8, 21, 43, 3, 7, 51, 62, 13, 68
output :3, 8, 7, 62, 13, 68, 21, 0, 43, 0, 51, 0, 53
思路:先排序,在按照规则输出。比较传统的思路,还可改进,一个数组分为奇数排列和偶数排列,空间省了,时间省不了。
空间要求:128byte
void solution2()
{
int arr[10];// = { 53, 8, 21, 43, 3, 7, 51, 62, 13, 68 };
int i1 = 0;
while (i1 < 10)
cin >> arr[i1++];
for (int i = 0; i < 10; i++)
{
bool isChange = false;
for (int j = 0; j < 9 - i; j++)
{
if (arr[j] > arr[j + 1])
{
isChange = true;
char t = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = t;
}
}
if (!isChange)
break;
}
for (int i = 0, k = 0, j = 1, c = 0; c < 10; j++)
{
if (j % 2 == 0)
{
int m = k;
for (; m < 10; m++)
{
if (arr[m] % 2 == 0)
{
cout << arr[m];
k = m + 1;
c++;
break;
}
}
if (m >= 10)
cout << 0;
}
else{
int m = i;
for (; m < 10; m++)
{
if (arr[m] % 2 != 0)
{
cout << arr[m];
i = m + 1;
c++;
break;
}
}
if (m >= 10)
cout << 0;
}
if (c >= 10)
cout << endl;
else
cout << " ";
}
}
3、比较难处理
思路:先计算单词出现次数,再按照最高次高输出。时间O(n + m)(n是字符串长度,m是不重复单词个数),空间消耗比较大O(2m)
void solution3()
{
vector <string> strVec;
vector <int> intVec;
string str = "Hello world, i said HELLO world to THe world.";
//cin >> str;
int i = 0, sta = 0;
while (str[i] != '\0')
{
while (str[sta] == ' ' || str[sta] == ',' || str[sta] == '.')
{
sta++;
i = sta;
}
if (str[i] >= 'A' && str[i] <= 'Z')
str[i] = tolower(str[i]);
if (str[i] == ' ' || str[i] == ',' || str[i] == '.')
{
int end = i - 1;
string temp = str.substr(sta, end - sta + 1);
int j = 0;
for (j = 0; j < strVec.size(); j++)
{
if (strVec[j] == temp)
{
intVec[j]++;
break;
}
}
if (strVec.size() <= j)
{
strVec.push_back(temp);
intVec.push_back(1);
}
sta = i + 1;
}
++i;
}
int f = 0, fi = INT_MIN, s = 0, si = INT_MIN;
for (int j = 0; j < intVec.size(); ++j)
{
if (intVec[j] > fi)
{
si = fi;
s = f;
fi = intVec[j];
f = j;
}
else if (intVec[j] > si)
{
si = intVec[j];
s = j;
}
}
cout << strVec[f] << "," << strVec[s];
}