簡體   English   中英

有什么方法可以改善此實現(顯着)?

[英]Any ways to improve this implementation (significantly)?

這是我為作業編寫的一段代碼。 看來可行,但我想知道是否錯過了什么。

任務是實現一個函數(在這里: Countwords ),該函數對char *中的所有單詞進行計數。 不應使用任何庫函數。

namespace {

bool IsPrintable(char c) {
  return c >= '!' && c <= '~';
}

void SkipPrintable(const char *&s) {
  do {
    s++;
  } while (IsPrintable(*s));
}

bool IsWhiteSpace(char c) {
  return c == ' ' || c == '\t' || c == '\n';
}

void SkipWhitespace(const char *&s) {
  while (IsWhiteSpace(*s)) {
      s++;
  }
}

} // namespace

int CountWords(const char *s) {
  int count = 0;

  while (*s != '\0') {
    SkipWhitespace(s);

    if (IsPrintable(*s)) {
        count++;
        SkipPrintable(s);
    }
  }

  return count;
}

您可以通過線性復雜度來解決此問題。 人們不能以更低的復雜度來做到這一點。 因此,您無法顯着改善算法。

沒有辦法顯着改進算法,但是可以通過使用一個類來表示解析器的狀態(例如當前索引和字符串本身)來使其更加清晰(這樣就不需要全部傳遞該算法了)。過度)。 您還可以通過實現一個使用bool (*ShouldSkip)(char)函數指針的單個SkipWhile函數,然后傳遞&IsWhitespace&IsPrintable ,來消除SkipPrintableSkipWhitespace之間的某些冗余。

我同意上述所有內容。 您的代碼已經足夠好了,重要的是它的線性性,所以您可以考慮的唯一有效的事情就是簡化它,例如

bool newWord = true;
int count = 0;
while(*s != '\0')
{
    if(!IsWhiteSpace(*s))
    {
        if(newWord)
        {
            newWord = false;
            count++;
        }
    }
    else
    {
        newWord = true;
    }
    s++;
}

但是我仍然認為您的實現沒有問題

為了簡化算法(就可讀性而言,而不是在計算復雜度方面),您可以計算單詞的開頭(其中非空白字符要么緊跟空白,要么是字符串中的第一個字符)。

char previousCharacter=' ';
int wordsCount=0;
while(*s)
{
  if(IsWhiteSpace(previousCharacter) && !IsWhiteSpace(*s))
    ++wordsCount;
  previousCharacter=*s;
  ++s;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM