[LeetCode]Longest Common Prefix

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

思考:依次比较字符串的第i个字符,不同退出循环。

class Solution {

public:

    string longestCommonPrefix(vector<string> &strs) {

        // IMPORTANT: Please reset any member data you declared, as

        // the same Solution instance will be reused for each test case.

        string res="";

		if(strs.size()==0) return res;

		if(strs.size()==1) return strs[0];

		int i,j;

		for(i=0;i<strs[0].size();i++)

		{

		    char temp=strs[0][i];

		    for(j=1;j<strs.size();j++)

		    {

		        if(strs[j].size()==i) return res;

		        if(strs[j][i]!=temp) return res;

		    }

		    res+=temp;

		}

		return res;

    }

};

  

你可能感兴趣的:(LeetCode)