面试题 42 翻转
(1)经典面试题: 翻转句子中的单词,并将单词的字母顺序翻转, 标点符号和字母一样处理
void Reverse(char *begin, char *end){ if(begin == NULL || end == NULL) return ; while(begin < end){ char tp = *begin; *begin = *end; *end = tp; begin++; end--; } } char * ReverseSentence(char *sentence){ if(sentence == NULL) return NULL; char *end = sentence; while(*end != ‘\0' )end++; end--; Reverse(sentence, end); char *begin = sentence; end = sentence; while(begin != '\0'){ while(*end != ' ' && *end != '\0') end++; Reverse(begin,end-1); while(*end == ' ') end++; begin = end; } return sebtence; }
(2)左旋若干个字符
char * LeftRotateString(char *str, int n){ //if(str == NULL) return str; int len = strlen(str); if(str == NULL || n <0 || n > len) return str; char *firstbegin = str; char *firstend = str + n-1; char * secondbegin = str + n; char * secondend = str +len -1; Reverse(firstbegin, firstend); Reverse(secondbegin, secondend); Reverse(firstbegin, secondend); return str; }
--------------------------------------------------------------------天道酬勤!
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步