【Leetcode 14】Longest Common Prefix
阿新 • • 發佈:2018-12-10
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string ""
.
Example 1:
Input: ["flower","flow","flight"] Output: "fl"
Example 2:
Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings.
題目翻譯:
一個vector<string> vec裡邊存了很多string,求這些string的最大相同的頭部分。
很簡單的題目,從頭依次遍歷即可,如果vec是空的,返回空,如果vec是1,則直接把結果返回,如果vec>=2,繼續查詢公共最大的範圍。
#include<iostream> #include<cmath> #include<string> #include<vector> using namespace std; class Solution{ public: string longestCommonPrefix(vector<string> &vec) { string str=""; int n=vec.size(); if(n==0) return str; if(n==1) { str=vec[0]; return str; } int count=0; int istrue=0; int max=vec[0].length(); while(count<max) { char temp=vec[0][count]; for(int i=1;i<n;i++) { if(temp!=vec[i][count]) istrue=1; } if(istrue==1) break; else count++; } for(int i=0;i<count;i++) str+=vec[0][i]; return str; } }; int main() { vector<string> vec; vec.push_back("flower"); vec.push_back("flow"); vec.push_back("flight"); Solution so; string str=so.longestCommonPrefix(vec); cout<<str<<endl; system("pause"); return 0; }