Leetcode – Longest common prefix

Tags: , ,

Longest common prefix

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

Pay attention to the corner case: strs can be empty. 

Analysis

We define cur to record the char at current round that is recorded by si

If si equals to the current string’s length, we return the substring from 0 to si

At the beginning of each round, cur is set as null. 

So when cur is null, we know this is the first string to check in current round. We set cur as the letter of the current string at index si 

For the following string, we check whether the char at si equals to cur. If they are not equal, that means the current letter is not in the common prefix. 

Java implementation.