题解 | #最长公共前缀#
最长公共前缀
https://www.nowcoder.com/practice/28eb3175488f4434a4a6207f6f484f47
//o(mn) o(1) #include <iostream> #include <iterator> class Solution { public: /** * * @param strs string字符串vector * @return string字符串 */ string longestCommonPrefix(vector<string>& strs) { // write code here if(strs.size()==0) return ""; int n=strs.size(); //遍历字符串数组中第一组 for(int i=0;i<strs[0].size();i++){ char temp=strs[0][i]; //遍历后续的每一组 for(int j=1;j<n;j++){ //比较每个字符串该位置是否和第一个相同 if (i==strs[j].size()||temp!=strs[j][i]) { return strs[0].substr(0,i); cout <<strs[0]<<endl; } } } return strs[0]; } };