Simple and fast solution using std::string
. You can read about std::string
here. It's powerful class that ships with standard library, if you master it, your life will become easier. Advantages of std::size_t
are discussed here
#include <iostream>
#include <string>
int main ()
{
std::string input;
std::cin >> input;
std::size_t curPos = 0;
std::size_t length = input.length();
std::size_t sw_offset = 0; // sw means 'shortest word'
std::size_t sw_length = 0;
std::size_t sw_count = 0;
while(curPos <= length)
{
std::size_t newPos = input.find_first_of(' ', curPos);
if(newPos == std::string::npos) // If there is no whitespace it means it's only 1 word
newPos = length;
if(newPos != curPos) // If word isn't empty (currentWordLength > 0)
{
std::size_t currentWordLength = newPos - curPos;
if(!sw_length || sw_length > currentWordLength)
{
sw_offset = curPos; // Store offset and length instead of copying
sw_length = currentWordLength;
sw_count = 1;
}
else if(sw_length == currentWordLength &&
input.substr(sw_offset, sw_length) == input.substr(curPos, currentWordLength))
{
++sw_count;
}
}
curPos = newPos + 1;
}
std::cout << "Fewest letter word is " << input.substr(sw_offset, sw_length)
<< " and it's appeared " << sw_count << " time(s)" << std::endl;
}
Same for c style strings
#include <iostream>
#include <cstring>
#include <algorithm>
int main ()
{
char input[256];
std::cin.get(input, sizeof(input));
std::size_t curPos = 0;
std::size_t length = strlen(input);
std::size_t sw_offset = 0;
std::size_t sw_length = 0;
std::size_t sw_count = 0;
while(curPos <= length)
{
std::size_t newPos = std::find(input + curPos, &input[sizeof(input) - 1], ' ') - input;
std::size_t currentWordLength = newPos - curPos;
if(currentWordLength > 0)
{
if(!sw_length || sw_length > currentWordLength)
{
sw_offset = curPos;
sw_length = currentWordLength;
sw_count = 1;
}
else if(sw_length == currentWordLength &&
strncmp(input + sw_offset, input + curPos, currentWordLength) == 0)
{
++sw_count;
}
}
curPos = newPos + 1;
}
char result[256];
strncpy(result, input + sw_offset, sw_length);
std::cout << "Fewest letter word is " << result
<< " and it's appeared " << sw_count << " time(s)" << std::endl;
}