题目链接:
题目介绍
描述
对于一个长度为 n 字符串,我们需要对它做一些变形。
首先这个字符串中包含着一些空格,就像"Hello World"一样,然后我们要做的是把这个字符串中由空格隔开的单词反序,同时反转每个字符的大小写。
比如"Hello World"变形后就变成了"wORLD hELLO"。
数据范围: 1≤n≤10^6 , 字符串中包括大写英文字母、小写英文字母、空格。
进阶:空间复杂度 O(n) , 时间复杂度 O(n)
输入描述:
给定一个字符串s以及它的长度n(1 ≤ n ≤ 10^6)
返回值描述:
请返回变形后的字符串。题目保证给定的字符串均由大小写字母和空格构成。
题目解法
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
/*
*BM83 字符串变形
描述
对于一个长度为 n 字符串,我们需要对它做一些变形。
首先这个字符串中包含着一些空格,就像"Hello World"一样,然后我们要做的是把这个字符串中由空格隔开的单词反序,
同时反转每个字符的大小写。
比如"Hello World"变形后就变成了"wORLD hELLO"。
数据范围: 1≤n≤10^6, 字符串中包括大写英文字母、小写英文字母、空格。
进阶:空间复杂度 O(n) , 时间复杂度 O(n)
输入描述:
给定一个字符串s以及它的长度n(1 ≤ n ≤ 10^6)
返回值描述:
请返回变形后的字符串。题目保证给定的字符串均由大小写字母和空格构成。
*/
//大小写转换
#define UPPER_LOWER(c) ((c >= 'a' && c <= 'z') ? (c-'a'+'A') : (c-'A'+'a'))
/**
*
* @param s string字符串
* @param n int整型
* @return string字符串
*/
char* trans(char* s, int n ) {
// char res[17]={0};
// printf("n = %d, input : %s", n, s);
// write code here
char *res = (char*)malloc(sizeof(char)*(n+2));
int wordLen = 0; //单词长度
char tmpc;
char *pCur;
//先整个字符串反转
for(int i=0; i<n; i++){
if(s[i] != ' ' && s[i] != '\0')
res[n-1-i] = UPPER_LOWER(s[i]);
else
res[n-1-i] = s[i];
}
res[n] = '\0'; //设置结束符
res[n+1] = '\0'; //设置结束符
pCur = res; //用pCur表示当前位置
while(*pCur != '\0')
{
wordLen = 0; //重置单词长度
while(*pCur != ' ' && *pCur != '\0'){ //获得单词长度
wordLen++;
pCur++;
}
for(int j=0; j<wordLen/2; j++){ //单词倒序
tmpc = pCur[-j-1];
pCur[-j-1] = pCur[-wordLen+j-1+1];
pCur[-wordLen+j-1+1] = tmpc;
}
pCur++; //跳过空格
}
return res;
}
/**************************end******************************************/
int main ()
{
char *s1 = "This is a sample";//16
char *ret = trans(s1, 16);
printf("\r\nret:");
printf("%s ", ret);
return 0;
}