How you can Discover the Shortest Phrase in C++


The problem

Easy, given a string of phrases, return the size of the shortest phrase(s).

The string won’t ever be empty and you don’t want to account for various information sorts.

The answer in C++

Choice 1:

int find_short(const std::string &str) {
    std::istringstream inp(str);
    std::string s;
    int len = -1;
    whereas (std::getline(inp, s, ' '))
        if (s.size() < len)
            len = s.size();
    return len;
}

Choice 2:

int find_short(std::string str) {
    std::istringstream iss(str);
    std::vector<std::string> vec{ std::istream_iterator<std::string>(iss), {} };
    return std::min_element(vec.start(), vec.finish(), [](const std::string& s1, const std::string& s2) { return s1.size() < s2.size(); })->size();
}

Choice 3:

#embrace <sstream>

int find_short(std::string str) {
  std::stringstream ss(str);
  auto buff = std::string();
  auto shorter = std::numeric_limits<size_t>::max();
  whereas (ss >> buff)
    shorter = min(shorter, buff.dimension());
  return shorter;
}

Check instances to validate our resolution

Describe(Exams)
{
  It(Sample_Test_Cases)
  {
    Assert::That(find_short("bitcoin take over the world perhaps who is aware of maybe"), Equals(3));
    Assert::That(find_short("seems random take a look at instances are simpler than writing out primary ones"), Equals(3));
    Assert::That(find_short("lets speak about javascript the most effective language"), Equals(3));
    Assert::That(find_short("i wish to journey the world writing code in the future"), Equals(1));
    Assert::That(find_short("Lets all go on vacation someplace very chilly"), Equals(2));
    Assert::That(find_short("Let's journey overseas lets"), Equals(2));
  }
};
See also  Does Your Dash Actually Even Want a Dash Objective?

Leave a Reply