Wednesday, February 21, 2024
HomeSoftware EngineeringThe best way to Discover the Shortest Phrase in C++

The best way to 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:

#embody <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 answer

Describe(Exams)
{
  It(Sample_Test_Cases)
  {
    Assert::That(find_short("bitcoin take over the world possibly who is aware of maybe"), Equals(3));
    Assert::That(find_short("seems random take a look at instances are simpler than writing out fundamental ones"), Equals(3));
    Assert::That(find_short("lets discuss javascript the very best language"), Equals(3));
    Assert::That(find_short("i need to journey the world writing code someday"), 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));
  }
};
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments