题目:
给你一个字符串数组 words,找出并返回 length (words [i]) * length (words [j]) 的最大值,并且这两个单词不含有公共字母。如果不存在这样的两个单词,返回 0。
分析:
- 先进行边界判断(数组为 null、长度不足 2、去重后元素不足 2 个的情况)
- 用 HashSet 对单词去重,避免重复计算
- 转为 ArrayList 便于通过索引遍历所有单词对
- 通过 isCommon 方法判断两个单词是否有公共字母(遍历字符 + indexOf 检查)
- 计算符合条件的单词对长度乘积,跟踪最大值
package 字符串数组;
import java.util.*;
public class Demo02 {
public static void main(String[] args) {
String[] strs = {"abc", "ab", "abcde", "abcd", "sx","abcdef"};
System.out.println("长度最大值:"+maxStringLength(strs));
}
public static int maxStringLength(String[] strs) {
if (strs == null) {
System.out.println("数组为null");
return 0;
}
if (strs.length < 2) {
System.out.println("数组长度不足2,无法判断");
return 0;
}
Set<String> set = new HashSet<>();
for (int i = 0; i < strs.length; i++) {
set.add(strs[i]);
}
if (set.size() < 2) {
System.out.println("数组中元素都相同,去重后为一个元素");
return 0;
}
int maxLen = 0;// 最长长度
List<String> list = new ArrayList<>(set);
for (int i = 0; i < list.size(); i++){
String str1 = list.get(i);
for (int j = i + 1; j < list.size(); j++){
String str2 = list.get(j);
if (!isCommon(str1, str2)){
int len = Math.max(maxLen, str1.length()*str2.length());
maxLen =len;
}
}
}
return maxLen;
}
public static Boolean isCommon(String str1, String str2){
for (Character s : str1.toCharArray()){
if (str2.indexOf(s) != -1){
// str2.indexOf如果查到,返回当前下标。如果没有查到,则返回-1
return true;
}
}
// 没有查到相同
return false;
}
}
运行结果: