*(leetcode_string) Longest Common Prefix

来源:互联网 发布:sql server安全策略 编辑:程序博客网 时间:2024/05/01 17:44

Longest Common Prefix

 Total Accepted: 26921 Total Submissions: 101490My Submissions

Write a function to find the longest common prefix string amongst an array of strings.

Show Tags
Have you met this question in a real interview? 
Yes
 
No

Discuss

class Solution {public:    string longestCommonPrefix(vector<string> &strs) {        int i,j;        char c;        string ans="";        if(strs.size()==0)  return ans; //注意判断为空的情况        for(i=0; ;i++){            if(i>=strs[0].length())  return ans;            c=strs[0][i];            for(j=1;j<strs.size();j++){                if(i>=strs[j].length()||c!=strs[j][i]){                    return ans;                }              }            ans+=c;        }        return ans;    }};


0 0
原创粉丝点击