太久没有写过LeetCode啦,今天刚好突然想起来,就找了道题目写一下,这次是用C++写的,因为最近在复习C++,正好这道题也简单,就写了一下,可能写的不咋样,大家就参考参考就行~
题目:
?
我把一些操作都分别用了不同的函数来写,应该也好理解,就不写详细思路了,应该都可以很容易看出来,这里有一个要注意的点就是 a e i o u不光是小写,还有大写也是属于同一种情况,加上就可以了
代码:
#include<iostream>
using namespace std;
class Solution {
public:
int count = 0;
string add(string subSentence) {
subSentence += "ma";
for (int i = 0; i < count; i++) {
subSentence += "a";
}
return subSentence;
}
string change(string subSentence) {
if (subSentence[0] == 'a' || subSentence[0] == 'e' || subSentence[0] == 'i' || subSentence[0] == 'o' || subSentence[0] == 'u' || subSentence[0] == 'A' || subSentence[0] == 'E' || subSentence[0] == 'I' || subSentence[0] == 'O' || subSentence[0] == 'U') {
subSentence = add(subSentence);
}
else {
// 移动字母再添加
char c = subSentence[0];
subSentence = subSentence.substr(1, subSentence.length());
subSentence += c;
subSentence = add(subSentence);
}
return subSentence;
}
string toGoatLatin(string sentence) {
int i = 0;
string newString = "";
string substring = "";
int length = sentence.length();
for (int k = 0; k < length; k++) {
if (sentence[k] == ' ') {
count += 1;
newString += change(substring);
newString += " ";
substring = "";
continue;
}
else if (k == (sentence.length() - 1)) {
substring += sentence[k];
count += 1;
newString += change(substring);
continue;
}
substring += sentence[k];
}
return newString;
}
};
int main()
{
Solution solution;
cout << solution.toGoatLatin("Each word consists of lowercase and uppercase letters only") << endl;
return 0;
}
|