Arn*_*shn 68 string algorithm data-structures
我有这个string s1 = "My name is X Y Z",我想扭转这些词的顺序s1 = "Z Y X is name My".
我可以使用额外的数组来做到这一点.我认为很难,但有可能在现场(不使用额外的数据结构)并且时间复杂度为O(n)吗?
Bil*_*ard 129
反转整个字符串,然后反转每个单词的字母.
第一次传递后,字符串将是
s1 = "Z Y X si eman yM"
Run Code Online (Sandbox Code Playgroud)
在第二次通过后,它将是
s1 = "Z Y X is name My"
Run Code Online (Sandbox Code Playgroud)
Dem*_*emi 33
将字符串反转,然后在第二遍中反转每个字......
在c#中,完全就地没有其他数组:
static char[] ReverseAllWords(char[] in_text)
{
int lindex = 0;
int rindex = in_text.Length - 1;
if (rindex > 1)
{
//reverse complete phrase
in_text = ReverseString(in_text, 0, rindex);
//reverse each word in resultant reversed phrase
for (rindex = 0; rindex <= in_text.Length; rindex++)
{
if (rindex == in_text.Length || in_text[rindex] == ' ')
{
in_text = ReverseString(in_text, lindex, rindex - 1);
lindex = rindex + 1;
}
}
}
return in_text;
}
static char[] ReverseString(char[] intext, int lindex, int rindex)
{
char tempc;
while (lindex < rindex)
{
tempc = intext[lindex];
intext[lindex++] = intext[rindex];
intext[rindex--] = tempc;
}
return intext;
}
Run Code Online (Sandbox Code Playgroud)
小智 14
Not exactly in place, but anyway: Python:
>>> a = "These pretzels are making me thirsty"
>>> " ".join(a.split()[::-1])
'thirsty me making are pretzels These'
Run Code Online (Sandbox Code Playgroud)
小智 13
在Smalltalk中:
'These pretzels are making me thirsty' subStrings reduce: [:a :b| b, ' ', a]
Run Code Online (Sandbox Code Playgroud)
我知道没有人关心Smalltalk,但它对我来说太美了.