1.最长公共前缀
描述
编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,输出空字符串 。
输入
首先输入一个整数n,表示接下来输入的字符串数量。
接着每行输入一个字符串。
输出
一行,一个表示最长公共前缀的字符串
样例输入
3
flower
flow
flight
样例输出
fl
#include#include #include using namespace std; int main() { int n; cin >> n; string* arr = new string[n]; int minlength = 1000; string result = ""; for (int i = 0; i < n; i++) //求所有字符串的最小长度 { cin >> arr[i]; if ((int)arr[i].length() < minlength) minlength = arr[i].length(); } if (n == 0) cout << result; else if (n == 1) cout << arr[0]; else { bool flag = true; //表示所有字符串的该位置上字符相同 for (int i = 0; i < minlength && flag; i++) //表示比较第i个字符 { char tmp = 'a'; for (int j = 0; j < n; j++) //表示取第j个字符串 { if (j == 0) //以第一个字符串为标准 { tmp = arr[j][i]; } else { if (tmp != arr[j][i]) { flag = false; break; } else { if (j == n - 1) //若比较到最后一个字符串仍相等,则记录该字符 result += tmp; } } } } cout << result; } return 0; }
2.字符串字母翻转
描述
输入带标点与空格的英文字符串(字符串长度不超过1000),将单词中除空格,标点符号之外的单词字母翻转顺序(即只对连续的大小写字母字符串翻转顺序)。
特别注意:
1、字符串中连续出现的多个空格均需要减少到一个空格,
2、输出结果的开头与结尾不能有空格
3、输入字符串包含英文大小写字母,空格,以及常用标点符号,并且输入字符串至少包含一个单词。
输入
一行,一个字符串
输出
一行,反转后的字符串
样例输入
the sky is blue!
样例输出
eht yks si eulb!
#include3.第一个只出现一次的字符 题目描述#include using namespace std; int main() { //读取字符串 char* input = new char[1000]{' ',' '}; char* output = new char[1000]{ ' ',' ' }; cin.getline(input, 1000); int lengthOfInput = strlen(input), iter=0, start=-1; bool blankInput =true; //初始化为true,则依照后续代码,第一个字母前的空格均被当做连续空格中的第x(x>1)个空格而忽略 //按照要求将输出字符串放到output数组中 for (int i = 0; i < lengthOfInput; i++) { if (input[i] <= 'Z' && input[i] >= 'A' || input[i] <= 'z' && input[i] >= 'a') //判断读取字符为字母 { if (start < 0) //找到新单词的第一个字母 { start = i; blankInput = false; } else //该单词的其他字母 continue; } else { if (input[i] == ' ' && blankInput) //忽略连续空格中的第x个空格 continue; if (start != -1) { //start!=-1,表示已经接收完成一个新单词;故将此单词反序输出,start重置为-1 for (int j = i - 1; j >= start; j--) output[iter++] = input[j]; start = -1; } if (input[i] == ' ') //当前字符为一串(或一个)空格中的第一个空格 blankInput = true; else //当前字符非空格,也非字母 blankInput = false; output[iter++] = input[i]; //当前字符(input[i])非字母,也非连续空格中的第x个空格 } if (i == lengthOfInput - 1 && start != -1) //最后一个字符串可能无输出条件,故需单独列出 { for (int j = i; j >= start; j--) output[iter++] = input[j]; } } if (output[iter] == ' ') iter--; output[iter++] = ' '; //注意加' '才能作为字符串输出!!! cout << output ; return 0; }
在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。 s 只包含小写字母。
解释 :
s = "abaccdeff"
返回 "b"
s = ""
返回 " "
限制:
0 <= s 的长度 <= 50000
样例1
输入:
abaccdeff
输出:
b
样例2
输入:
aabb
输出:
#include#include using namespace std; char FirstOnceChar(char* s) { int i = 0; int count = 0; while (s[i] != ' ') //到字符串末尾 { for (int j = 0; j 1) { i++; count = 0; } if (count == 1) return s[i]; } } int main() { char a[50000]; cin >> a; if (a == "") { cout << " "<



