题目描述:

image-20250506152059372

代码:

package interview;

/**
* @author hxw
* @create 2025-05-06-8:33
* @Description: 14. 最长公共前缀 简单
*/
public class fourteen {
public static void main(String[] args) {
String[] strs = new String[]{"dog","racecar","car"};
System.out.println(new Solution().longestCommonPrefix(strs));

}
/**
* 目的:编写一个函数来查找字符串数组中的最长公共前缀。
* 如果不存在公共前缀,返回空字符串 ""。
*
* 思路:拿第一个字符串的前缀和后面的字符串比较,如果相同则继续拿后面的字符串的相同前缀和后面的字符串比较,直到比较到最后一个字符串。
*/
static class Solution {
public String longestCommonPrefix(String[] strs) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < strs[0].length(); i++) {
for (int j = 1; j < strs.length; j++) {
if (i >= strs[j].length() || strs[j].charAt(i) != strs[0].charAt(i)) {
return sb.toString();
}
}
sb.append(strs[0].charAt(i));
}
return sb.toString();
}
}
}