Find the longest sequence of prefix shared by all the words in a string

Source (I guess) This version has the minimum comparisons required for the solution.

#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main() {
  int n;
  cin >> n;
  vector<string> strs;
  while (n--) {
    string tmp;
    cin >> tmp;
    strs.push_back(tmp);
  }
  int len = 0;
  while (len < strs[0].size()) {
    char cur = strs[0].at(len);
    if (std::all_of(strs.begin() + 1,
                    strs.end(),
                    [len,cur](const string&amp; t) {
                        return len &lt; t.size() &amp;&amp; t.at(len) == cur; })) {
      ++len;
    } else {
      break;
    }
  }
  cout &lt;&lt; len &lt;&lt; std::endl;
  return 0;
}
Advertisements

About Avi Dullu
Jaako rakhe saiyan, maar sake na koi!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: