最長(zhǎng)公共前綴
public class LongestCommonPrefix {
public String longestCommonPrefix(String[] strs) {
// 如果字符串?dāng)?shù)組為空或長(zhǎng)度為0,返回空字符串
if (strs == null || strs.length == 0) {
return "";
}
// 取第一個(gè)字符串作為初始前綴
String prefix = strs[0];
// 遍歷字符串?dāng)?shù)組的其他字符串
for (int i = 1; i < strs.length; i++) {
// 比較當(dāng)前字符串與當(dāng)前前綴
while (strs[i].indexOf(prefix) != 0) {
// 縮短前綴
prefix = prefix.substring(0, prefix.length() - 1);
// 如果前綴為空,返回空字符串
if (prefix.isEmpty()) {
return "";
}
}
}
// 返回最長(zhǎng)公共前綴
return prefix;
}
public static void main(String[] args) {
LongestCommonPrefix solution = new LongestCommonPrefix();
String[] strs = {"flower", "flow", "flight"};
System.out.println(solution.longestCommonPrefix(strs)); // 輸出 "fl"
}
}
兩元素的和等于目標(biāo)值
import java.util.HashMap;
import java.util.Map;
public class TwoSum {
public int[] twoSum(int[] nums, int target) {
// 創(chuàng)建哈希表用于存儲(chǔ)數(shù)值及其下標(biāo)
Map<Integer, Integer> map = new HashMap<>();
// 遍歷數(shù)組中的每個(gè)元素
for (int i = 0; i < nums.length; i++) {
// 計(jì)算目標(biāo)值與當(dāng)前元素的差值
int complement = target - nums[i];
// 檢查該差值是否存在于哈希表中
if (map.containsKey(complement)) {
// 如果存在,則返回當(dāng)前元素的下標(biāo)和該差值對(duì)應(yīng)的下標(biāo)
return new int[] { map.get(complement), i };
}
// 將當(dāng)前元素及其下標(biāo)存入哈希表
map.put(nums[i], i);
}
// 如果未找到符合條件的兩個(gè)數(shù),返回空數(shù)組
return new int[0];
}
public static void main(String[] args) {
TwoSum solution = new TwoSum();
int[] nums = {2, 7, 11, 15};
int target = 9;
int[] result = solution.twoSum(nums, target);
System.out.println("Indices: [" + result[0] + ", " + result[1] + "]"); // 輸出 "Indices: [0, 1]"
}
}