颠倒单词的顺序——时间复杂度?
输入:“我的名字是普里塔姆” 输出:“Pritam is Name My”
到目前为止我已经写了这个,但是我对时间复杂度有点困惑
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) 解决方案。如果我错了,请纠正我。大家有没有更好的解决办法。
Input: "My Name is Pritam"
Output: "Pritam is Name My"
I have written this so far, but I'm bit confused with time complexity
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;
}
When I call ReverseString method from a for loop I think it no more a O(n) solution. Please correct me if I'm wrong. Does anyone have any better solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
爪哇语
in Java
您的代码是
O(n)
。您可以通过查看每个元素涉及的交换次数来看到这一点,即 2(一次用于整个字符串的初始反转,第二次用于逐字反转)。此外,foreach
循环对每个元素精确地迭代一次。Your code is
O(n)
. You can see this by looking at the number of swaps each element is involved in, which is 2 (once for the initial reverse of the entire string, second for the word-wise reversal). In addition theforeach
loop iterates over each element exactly once.在红宝石中:
In Ruby:
在C中;
In C;
可能重复,我不久前曾问过类似的问题。但我收到的回复非常有趣,实际上它确实改变了对复杂性的思考方式;).... 时间复杂度
Possible duplicate, I had asked a similar question some time back. But the responses I received were very interesting, actually it did change the way complexity should be thought about ;).... Time Complexity
分割字符串并将其压入堆栈。从堆栈中弹出元素并将其添加到新字符串中。需要额外的空间,但只是发布,因为它可能是实现字符串反转的简单方法
}
Split the string and push it to a stack . Pop elements from stack and add it to a new string. Requires extra space,but just posted because it could be a easy way to implement string reverse
}
在Python中,
in Python,