**一. 题目描述**
Write a function to find the longest common prefix string amongst an array of strings.
**二. 题目分析**
题目的大意是,给定一组字符串,找出所有字符串的最长公共前缀。
对比两个字符串的最长公共前缀,其前缀的长度肯定不会超过两个字符串中较短的长度,设最短的字符串长度为`n`,那么只要比较这两个字符串的前`n`个字符即可。
使用变量`prefix`保存两个字符串的最长公共前缀,再将`prefix`作为一个新的字符串与数组中的下一个字符串比较,以此类推。
一个特殊情况是,若数组中的某个字符串长度为`0`,或者求得的当前最长公共前缀的长度为`0`,就直接返回空字符串。
**三. 示例代码**
~~~
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
string longestCommonPrefix(vector<string> &strs)
{
if (strs.size() == 0)
return "";
string prefix = strs[0];
for (int i = 1; i < strs.size(); ++i)
{
if (prefix.length() == 0 || strs[i].length() == 0)
return "";
int len = prefix.length() < strs[i].length() ? prefix.length() : strs[i].length();
int j;
for (j = 0; j < len; ++j)
{
if (prefix[j] != strs[i][j])
break;
}
prefix = prefix.substr(0,j);
}
return prefix;
}
};
~~~
![](https://box.kancloud.cn/2016-01-05_568bb5efdf922.jpg)
**四. 小结**
该题思路不难,而且还有几种相似的解决思路,在实现时需要做到尽量减少比较字符的操作次数。
- 前言
- 2Sum
- 3Sum
- 4Sum
- 3Sum Closest
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array II
- Search in Rotated Sorted Array
- Remove Element
- Merge Sorted Array
- Add Binary
- Valid Palindrome
- Permutation Sequence
- Single Number
- Single Number II
- Gray Code(2016腾讯软件开发笔试题)
- Valid Sudoku
- Rotate Image
- Power of two
- Plus One
- Gas Station
- Set Matrix Zeroes
- Count and Say
- Climbing Stairs(斐波那契数列问题)
- Remove Nth Node From End of List
- Linked List Cycle
- Linked List Cycle 2
- Integer to Roman
- Roman to Integer
- Valid Parentheses
- Reorder List
- Path Sum
- Simplify Path
- Trapping Rain Water
- Path Sum II
- Factorial Trailing Zeroes
- Sudoku Solver
- Isomorphic Strings
- String to Integer (atoi)
- Largest Rectangle in Histogram
- Binary Tree Preorder Traversal
- Evaluate Reverse Polish Notation(逆波兰式的计算)
- Maximum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Longest Common Prefix
- Recover Binary Search Tree
- Binary Tree Level Order Traversal
- Binary Tree Level Order Traversal II
- Binary Tree Zigzag Level Order Traversal
- Sum Root to Leaf Numbers
- Anagrams
- Unique Paths
- Unique Paths II
- Triangle
- Maximum Subarray(最大子串和问题)
- House Robber
- House Robber II
- Happy Number
- Interlaving String
- Minimum Path Sum
- Edit Distance
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock IV
- Decode Ways
- N-Queens
- N-Queens II
- Restore IP Addresses
- Combination Sum
- Combination Sum II
- Combination Sum III
- Construct Binary Tree from Inorder and Postorder Traversal
- Construct Binary Tree from Preorder and Inorder Traversal
- Longest Consecutive Sequence
- Word Search
- Word Search II
- Word Ladder
- Spiral Matrix
- Jump Game
- Jump Game II
- Longest Substring Without Repeating Characters
- First Missing Positive
- Sort Colors
- Search for a Range
- First Bad Version
- Search Insert Position
- Wildcard Matching