g0001_0100.s0014_longest_common_prefix.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java21 Show documentation
Show all versions of leetcode-in-java21 Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g0001_0100.s0014_longest_common_prefix;
// #Easy #Top_Interview_Questions #String #Level_2_Day_2_String #Udemy_Strings
// #2023_08_09_Time_0_ms_(100.00%)_Space_40.2_MB_(83.48%)
/**
* 14 - Longest Common Prefix\.
*
* Easy
*
* Write a function to find the longest common prefix string amongst an array of strings.
*
* If there is no common prefix, return an empty string `""`.
*
* **Example 1:**
*
* **Input:** strs = ["flower","flow","flight"]
*
* **Output:** "fl"
*
* **Example 2:**
*
* **Input:** strs = ["dog","racecar","car"]
*
* **Output:** ""
*
* **Explanation:** There is no common prefix among the input strings.
*
* **Constraints:**
*
* * `1 <= strs.length <= 200`
* * `0 <= strs[i].length <= 200`
* * `strs[i]` consists of only lower-case English letters.
**/
public class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs.length < 1) {
return "";
}
if (strs.length == 1) {
return strs[0];
}
String temp = strs[0];
int i = 1;
String cur;
while (temp.length() > 0 && i < strs.length) {
if (temp.length() > strs[i].length()) {
temp = temp.substring(0, strs[i].length());
}
cur = strs[i].substring(0, temp.length());
if (!cur.equals(temp)) {
temp = temp.substring(0, temp.length() - 1);
} else {
i++;
}
}
return temp;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy