Task: Given an array of strings, Find the longest common prefix among all the strings in the array.
Example:
Input:
1
4
geeksforgeeks geeks geek geezer
Output:
gee
Here is the Code:
Program in C++:
- #include<iostream>
- using namespace std;
- void longestCommonPrefix(string *a,int n)
- {
- string s1= a[0];
- for(int i=1;i<n;i++)
- {
- string s2=a[i];
- int j=0;
- while(j<s1.length())
- {
- if(s1[j]==s2[j])
- {
- j++;
- }
- else
- {
- s1.erase(j,s1.length());
- break;
- }
- }
- }
- if(s1.length()==0)
- {
- cout<<-1;
- }
- else
- {
- cout<<s1;
- }
- return;
- }
- int main()
- {
- int t;
- cin>>t;
- while(t--)
- {
- int n;
- cin>>n;
- string a[n];
- for(int i=0;i<n;i++)
- {
- cin>>a[i];
- }
- longestCommonPrefix(a,n);
- cout<<endl;
- }
- return 0;
- }
Here is the Video:
Comments
Post a Comment