此题是非常经典的字符串的颠倒问题,但这个更复杂一些,但也不其本质,我此次写的方式是用双指针问题完成的,虽然算不上什么好方法,但如果各位看官觉得满意的话,请各位给我个点个免费的赞吧,谢谢了_
1.题目要求如图所示:
2.接下来是做题的步骤:
我们先把字符串的颠倒函数写好,如图所示:
void reverse(char* left,char* right)
{
while(left <= right)
{
char str = *left;
*left = *right;
*right = str;
left++;
right--;
}
}
(1).我们先把整个字符串都颠倒过来,如图所示:
char* left = s;
char* right = s + strlen(s) - 1;
//先进行字符串逆置
reverse(left,right);
(2).然后再让各个单词颠倒过来,如图所示:
char* start = s;
while(*start != '\0')
{
while(*start == ' '&&*start != '\0')
{
start++;
}
char* end = start;
while(*end != ' '&&*end != '\0')
{
end++;
}
reverse(start,end-1);
if(*end != '\0')
{
end++;
}
start = end;
}
(3)此时各个单词颠倒过来后,我们就先把字符串首尾的括号去掉,我是用malloc函数辅助我这一想法的_,如图所示:
left = s;
right = s + strlen(s) - 1;
//头尾括号
while (*left == ' ')
left++;
while(*right == ' ')
right--;
char* string = (char*)malloc(sizeof(char) * (strlen(s) + 1));
int j = 0;
while(left <= right&&*left != '\0')
{
*(string + j) = *left;
j++;
left++;
}
*(string + j) = '\0';
(4).然后我们再去掉单词之间的括号,如图所示:
int s_size = 0;
int i = 0;
while(i < j)
{
if(string[i] == ' '&&string[i] != '\0')
{
s[s_size] = string[i];
s_size++;
i++;
if(i >= j)
break;
while(string[i] == ' ')
{
i++;
if(i >= j)
break;
}
}else{
s[s_size] = string[i];
s_size++;
i++;
if(i >= j)
break;
}
}
s[s_size] = '\0';
(5).全部代码如下图所示:
//字符串逆置函数
void reverse(char* left,char* right)
{
while(left <= right)
{
char str = *left;
*left = *right;
*right = str;
left++;
right--;
}
}
char* reverseWords(char* s) {
char* ret = s;
char* left = s;
char* right = s + strlen(s) - 1;
//先进行字符串逆置
reverse(left,right);
//然后再让单词进行逆置
char* start = s;
while(*start != '\0')
{
while(*start == ' '&&*start != '\0')
{
start++;
}
char* end = start;
while(*end != ' '&&*end != '\0')
{
end++;
}
reverse(start,end-1);
if(*end != '\0')
{
end++;
}
start = end;
}
left = s;
right = s + strlen(s) - 1;
//去掉头尾括号
while (*left == ' ')
left++;
while(*right == ' ')
right--;
char* string = (char*)malloc(sizeof(char) * (strlen(s) + 1));
int j = 0;
while(left <= right&&*left != '\0')
{
*(string + j) = *left;
j++;
left++;
}
*(string + j) = '\0';
//去掉单词之间的括号
int s_size = 0;
int i = 0;
while(i < j)
{
if(string[i] == ' '&&string[i] != '\0')
{
s[s_size] = string[i];
s_size++;
i++;
if(i >= j)
break;
while(string[i] == ' ')
{
i++;
if(i >= j)
break;
}
}else{
s[s_size] = string[i];
s_size++;
i++;
if(i >= j)
break;
}
}
s[s_size] = '\0';
return ret;
}
好了,各位看官,这就是我的代码,各位看官如果觉得满意的话就给个免费的赞吧,谢谢各位了。
标签:151,char,right,++,单词,start,while,Leetcode,left From: https://blog.csdn.net/m0_54244065/article/details/139440030