我碰到這個文章來Reverse words in a given string爲什麼單詞O(n)的句子的逆時間複雜度?
的代碼是
void reverseWords(char *s)
{
char *word_begin = NULL;
char *temp = s; /* temp is for word boundry */
/*STEP 1 of the above algorithm */
while(*temp)
{
/*This condition is to make sure that the string start with
valid character (not space) only*/
if ((word_begin == NULL) && (*temp != ' '))
{
word_begin=temp;
}
if(word_begin && ((*(temp+1) == ' ') || (*(temp+1) == '\0')))
{
reverse(word_begin, temp);
word_begin = NULL;
}
temp++;
} /* End of while */
/*STEP 2 of the above algorithm */
reverse(s, temp-1);
}
我的時間複雜度的理解這個問題:
1)遍歷整個字符串,因此O(n)
,n = length of the array
2 )反向時間複雜度爲O(m/2)
m = size of word reversing
爲什麼不是時間複雜度O(n * (m/2))
這是O(nm) ?
但在鏈接中提到的時間複雜度爲O(n)
。的reverse method?
當你說逆時間複雜度是'O(n/2)'時,'n'是什麼?你正在翻轉的單詞的大小?對於整個字符串,與'O(n)'中的'n'不同嗎?那麼爲什麼爲兩個不同的值使用相同的變量? –
我根據你的問題編輯了這個問題。 – Newbie
那麼'n'和'm'之間的關係是什麼?他們顯然不是獨立的。例如,200個字母的句子不能有300個字母的單詞,對吧?另外,每次迭代都不會調用「reverse」,僅在某些情況下。所以你不能只乘以它們。 (不斷修正你的錯誤,你最終會同意給出的答案。) –