feat: 2025-10-28打卡
This commit is contained in:
32
14.longest-common-prefix.java
Normal file
32
14.longest-common-prefix.java
Normal file
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* @lc app=leetcode id=14 lang=java
|
||||
*
|
||||
* [14] Longest Common Prefix
|
||||
*/
|
||||
|
||||
// @lc code=start
|
||||
class Solution {
|
||||
public String longestCommonPrefix(String[] strs) {
|
||||
if(strs == null || strs.length == 0) {
|
||||
return "";
|
||||
}
|
||||
String r = strs[0];
|
||||
for(int i=1; i<strs.length;i++) {
|
||||
r = longestCommonPrefix(r, strs[i]);
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
private String longestCommonPrefix(String a, String b) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for(int i = 0; i<a.length() && i<b.length();i++) {
|
||||
if(a.charAt(i) != b.charAt(i)) {
|
||||
break;
|
||||
}
|
||||
sb.append(a.charAt(i));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
// @lc code=end
|
||||
|
||||
Reference in New Issue
Block a user