[英]Reverse words in a sentence with space complexity o(1)
I got one question: to reverse the words in a sentence.我有一个问题:将句子中的单词颠倒过来。 eg the original string is Mike loves music
, after conversion, it should be music loves Mike
;例如原字符串是Mike loves music
,转换后就是music loves Mike
;
my approach is simple:我的方法很简单:
const reverse = (str: string) => str.split(' ').reverse().join(' ');
the space complexity is o(n)
空间复杂度为o(n)
However, the follow up question is how to convert it with space complexity o(1)
.但是,后续问题是如何将其转换为空间复杂度o(1)
。
I am thinking to use two pointers, but seems too complex.我正在考虑使用两个指针,但似乎太复杂了。 Please advise.请指教。
Simply简单地
"yourText".split("").reverse().join(""); "yourText".split("").reverse().join("");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.