Longest Common Prefix
Total Accepted: 44093 Total Submissions: 169565My Submissions
Question Solution
Write a function to find the longest common prefix string amongst an array of strings.
Hide Tags
Have you met this question in a real interview?
Yes
No
这是一道简单题,找出一系列字符串中的最长的前缀字符串
#include<iostream> #include<string> #include <vector> using namespace std; string longestCommonPrefix(vector<string>& strs) { string result; if(strs.empty()) return result; if(strs.size()==1) { result=strs[0]; return result; } int len1=strs[0].size(); for(int j=0;j<len1;++j) { result.push_back((strs[0])[j]); int len2=strs.size(); for(int i=0;i<len2;++i) { int len3=strs[i].size(); if(j>=len3) { result.pop_back(); return result; } if((strs[0])[j]!=(strs[i])[j]) { result.pop_back(); return result; } } } return result; } int main() { vector<string> str; str.push_back("asdf"); str.push_back("asdgk"); str.push_back("asd"); cout<<longestCommonPrefix(str)<<endl; }
时间: 2024-10-12 09:28:33