Problem
Write a function to find the longest common prefix string amongst an array of strings.Code
string longestCommonPrefix(vector<string> &strs) { // Note: The Solution object is instantiated only once and is reused by each test case. int n = strs.size(); if(n == 0) return ""; string prefix = strs[0]; for(int i = 1; i < n; ++i){ int j = 0; int m = prefix.size(); while(j < m && strs[i][j] == prefix[j]) ++j; if(j == 0) return ""; prefix = prefix.substr(0,j); } return prefix; }
No comments:
Post a Comment