参考链接:
https://leetcode-cn.com/problems/fan-zhuan-dan-ci-shun-xu-lcof/solution/yi-ge-mo-ban-shua-bian-suo-you-zi-fu-chu-x6vh/
class Solution {
public:
int lengthOfLastWord(string s) {
if(s.empty()){
return 0;
}
s += " ";这里在最后一个字符位置加上空格,这样最后一个字符串就不会遗漏
vectorres;
string temp = "";
for(char x:s){
if(x == ' '){
if(!temp.empty()){要不要判断非空取决于给定的字符串有没有前置或者后置的空格
res.push_back(temp);
temp.clear();
}
}else{
temp += x;
}
}
if(res.empty()){
return 0;
}
return res.back().size();
}
};
class Solution {
public:
string reverseWords(string s) {
if(s.empty()){
return 0;
}
s += " ";
vectorres;
string temp = "";
for(char x:s){
if(x == ' '){
res.push_back(temp);
temp.clear();
}else{
temp += x;
}
}
s.clear();
for(string &m:res){
reverse(m.begin(),m.end());
s += m + ' ';
}
s.pop_back(); //注意最后多加了一个空格要去掉
return s;
}
};
class Solution {
public:
string reverseWords(string s) {
if(s.empty()){
return "";
}
s += " ";
vectorres;
string temp = "";
for(char x:s){
if(x == ' '){
if(!temp.empty()){
res.push_back(temp);
temp.clear();
}
}else{
temp += x;
}
}
s.clear();
reverse(res.begin(),res.end());
for(string m:res){
s += m + ' ';
}
s.pop_back();
return s;
}
};
class Solution {
public:
string truncateSentence(string s, int k) {
if(s.empty()){
return "";
}
s+=" ";
string temp = "";
vectorres;
for(char x:s){
if(x == ' '){
res.push_back(temp);
temp.clear();
}else{
temp += x;
}
}
s.clear();
// int m = 0;
// for(string &x:res){
// s += x + ' ';
// m++;
// if(m == k){
// break;
// }
// }
for(int i =0;i < k;i++){
s += res[i]+' ';
}
s.pop_back();
return s;
}
};
class Solution:
def truncateSentence(self, s: str, k: int) -> str:
return ' '.join(s.split(' ')[:k])
class Solution {
public:
int numDifferentIntegers(string word) {
sets;
word += 'a';//以防止最后一个是数字
string temp = "";
for(char x:word){
if(isalpha(x)){
if(!temp.empty()){
s.insert(temp);//在集合中插入数字
temp.clear();
}
}else{//遇到数字
if(temp == "0"){//数字前导为0
temp.clear();
}
temp += x;
}
}
return s.size();//集合去重,集合大小就是所有整数长度
}
};
class Solution {
public:
string mostCommonWord(string paragraph, vector& banned) {
paragraph += " ";
string temp = "";
setban(banned.begin(),banned.end());
maps;
for(char x:paragraph){
if(!isalpha(x)){
if(!temp.empty()){
s[temp]++;//对每一个单词计数
temp.clear();
}
}else{
temp += tolower(x);//转小写
}
}
vectorwords;
for(auto p:s){
words.push_back(p.first);
}
sort(words.begin(),words.end(),[&](string &p,string &q){return s[p]>s[q];}); //按照频次降序
if(ban.empty()){//如果没有禁用单词,直接返回排序后列表首元素
return words[0];
}
for(auto w:words){
if(ban.find(w) == ban.end()){
return w;
}
}
return "";
}
};
class Solution {
public:
string toGoatLatin(string sentence) {
sentence += " ";
string temp = "";
vectorres;
string vowels = "aeiouAEIOU";
for(char x:sentence){
if(x == ' '){
res.push_back(temp);
temp.clear();
}else{
temp += x;
}
}
sentence.clear();
for(int i = 0; i 


