【LEETCODE】43、1002. Find Common Characters
2024-10-21 03:53:35
package y2019.Algorithm.array; import java.util.*; /**
* @ProjectName: cutter-point
* @Package: y2019.Algorithm.array
* @ClassName: CommonChars
* @Author: xiaof
* @Description: 1002. Find Common Characters
* Given an array A of strings made only from lowercase letters, return a list of all characters that show up in all strings
* within the list (including duplicates).
* For example, if a character occurs 3 times in all strings but not 4 times, you need to include that character three times
* in the final answer.
* You may return the answer in any order.
*
* Input: ["bella","label","roller"]
* Output: ["e","l","l"]
*
* @Date: 2019/7/4 11:07
* @Version: 1.0
*/
public class CommonChars { public List<String> solution(String[] A) {
List<String> result = new ArrayList<>();
int[] nums = new int[26]; //英文一共26个字符,并且是小写的
Arrays.fill(nums, Integer.MAX_VALUE);
//遍历所有的字符,根据小标放入集合中
for(String aTemp : A) {
//依次遍历所有字符
char tempC[] = aTemp.toCharArray();
int[] cnt = new int[26];
//第一次统计每个单词中出现的次数
for(int j = 0; j < tempC.length; ++j) {
cnt[tempC[j] - 'a']++;
}
//第二次我们过滤掉,每二个单词中出现的最小次数,比如第一个单词出现10次,但是第二个单词出现1次,那么都出现的次数也就是1次
for(int i = 0; i < nums.length; ++i) {
nums[i] = Math.min(nums[i], cnt[i]);
}
} //最后统计结果
for(int i = 0; i < nums.length; ++i) {
for(int j = 0; j < nums[i]; ++j) {
//如果出现多处,那么放入多处
result.add("" + (char) ('a' + i));
}
} //如果每个字符中都出现过,那么必须是3的倍数次
return result;
} public List<String> commonChars(String[] A) {
List<String> ans = new ArrayList<>();
int[] count = new int[26];
Arrays.fill(count, Integer.MAX_VALUE);
for (String str : A) {
int[] cnt = new int[26];
for (int i = 0; i < str.length(); ++i) { ++cnt[str.charAt(i) - 'a']; } // count each char's frequency in string str.
for (int i = 0; i < 26; ++i) { count[i] = Math.min(cnt[i], count[i]); } // update minimum frequency.
}
for (char c = 'a'; c <= 'z'; ++c) {
while (count[c - 'a']-- > 0) { ans.add("" + c); }
}
return ans;
} public static void main(String args[]) {
String as[] = {"bella","label","roller"};
CommonChars fuc = new CommonChars();
System.out.println(fuc.solution(as));
}
}
最新文章
- cookies如何成为全局变量以及设置,删除,获取
- JQuery ajax调用一直回调error函数
- [译] MongoDB Java异步驱动快速指南
- Office组件之Spire.XLS的DotNet操作
- 在VC项目中使用自定义资源
- LINE最新版6.5.0在iOS上的删除信息取证
- 控制反转(IoC)与依赖注入(DI)
- Java开发笔记(五十六)利用枚举类型实现高级常量
- 一分钟学会JavaMail(假)__手动滑稽
- BindingResult 作用原理
- linux 系统调用之文件操作
- sql server开发工具
- AIOps指导
- 转:【专题十二】实现一个简单的FTP服务器
- 位(bit)、字节(Byte)、MB(兆位)之间的换算关系
- 3.Appium处理原生与H5的嵌套
- Spring Cloud 与 Dubbo、Spring Cloud 与 Docker、Spring Cloud 与 Kubernetes 比较
- /.well-known/apple-app-site-association
- 页面的缓存设置与meta的作用详细解释
- 【采集层】Kafka 与 Flume 如何选择
热门文章
- proxysql 学习一 proxysql docker 运行试用
- ShardingSphere初探1 --Sharding-JDBC
- 开源项目 01 HtmlAgilityPack
- GDOI2018 小学生图论题 [NTT]
- QML学习(二)——<;QML语法>;
- PL/SQL Developer插入数据到数据库出现数据中文乱码
- SpringMVC(中)
- centos6.10中部署percona-mysql双实例的方法
- 十三、postman导出java代码
- MongoDB学习(附录一) 安装mongodb3.6时碰到的问题