14. Longest Common Prefix

来源:互联网 发布:java.io jar包下载 编辑:程序博客网 时间:2024/06/06 07:16

1.Question

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

2.Code

class Solution {public:    string longestCommonPrefix(vector<string>& strs) {        string res = "";        if(strs.empty()) return res;        int label = 0;        while(1)        {            char current = strs[0][label];            if(current == '\0') return res;            for(int i = 1, size = strs.size(); i < size; i++)            {                if(current != strs[i][label]) return res;            }            res += current;            label++;        }    }};

3.Note

a. 直接扫一遍就好了。注意终止条件。并注意string的末尾是'\0'。

b. for的判断语句里尽量不要写函数,否则调用多次费时间。

0 0