输入:“我的名字是 Pritam” 输出:“Pritam 是我的名字”
到目前为止我已经写了这个,但是我对时间复杂度有点困惑
public string ReverseWordsInAString(string str)
{
char[] temp = str.ToCharArray();
int startIndex = 0;
int endIndex = str.Length - 1;
temp = ReverseString(temp, startIndex, endIndex);
endIndex = 0;
foreach (char c in temp)
{
if(c == ' ')
{
temp = ReverseString(temp, startIndex, endIndex-1);
startIndex = endIndex + 1;
}
if (endIndex == str.Length-1)
{
temp = ReverseString(temp, startIndex, endIndex);
}
endIndex++;
}
str = new string(temp);
return str;
}
public char[] ReverseString(char[] chr, int start, int end)
{
while (start < end)
{
char temp = chr[start];
chr[start] = chr[end];
chr[end] = temp;
start++;
end--;
}
return chr;
}
当我从 for 循环调用 ReverseString 方法时,我认为它不再是 O(n) 解决方案。如果我错了,请纠正我。有没有人有更好的解决方案。
最佳答案
在Java中
String str= "My Name is Pritam";
String arr[] = str.split(" ");
for(int i = arr.length-1 ; i >=0 ; i--){
System.out.println(arr[i]);
}
关于algorithm - 颠倒单词的顺序——时间复杂度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5895185/