gpt4 book ai didi

c++ - 紧凑、可读、高效的 C++ 算法,用于反转字符串中的单词 IN-PLACE

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:44:53 24 4
gpt4 key购买 nike

<分区>

所以我正在尝试针对提示提出一个好的 C++ 解决方案

"Reverse words in a string (words are separated by one or more spaces). Now do it in-place. By far the most popular string question!"

而我现在拥有的是一个怪物:

void reverse_words ( std::string & S )
{
/*
Programming interview question: "Reverse words in a string (words are separated by one or more spaces). Now do it in-place. By far the most popular string question!"
http://maxnoy.com/interviews.html
*/
if (S.empty()) return;
std::string::iterator ita = S.begin() , itb = S.end() - 1;
while (ita != itb)
{
if (*ita != ' ')
{
std::string sa; // string to hold the current leftmost sequence of non-whitespace characters
std::string::iterator tempa = ita; // iterator to the beginning of sa within S
while (ita != ' ' && ita != itb) sa.push_back(*ita++); // fill sa
while (*itb == ' ' && itb != ita) --itb; // move itb back to the first non-whitespace character preceding it
std::string sb; // string to hold the current rightmost sequence of non-whitespace characters
std::string::iterator tempb = itb; // iterator to the end of sb within S
while (*itb != ' ' && itb != ita) sb.push_back(*itb--); // fill sb
S.replace(tempa, ita-tempa, sb); // replace the current leftmost string with the current rightmost one
S.replace(tempb, itb-tempb, sa); // and vice-versa
}
else
{
++ita;
}
}
}

我认为我的想法是正确的(找到第一个字符串,将其与最后一个字符串交换,找到第一个字符串之后的下一个字符串,将其与最后一个字符串之前的字符串交换,等等),但我需要一些更好的工具来让这一切发生。我如何利用标准库来解决这个问题?

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com