首页 技术 正文
技术 2022年11月15日
0 收藏 949 点赞 3,447 浏览 1491 个字

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.

Example 1:

1
2
Input: ["bella","label","roller"]
Output: ["e","l","l"]

Example 2:

1
2
Input: ["cool","lock","cook"]
Output: ["c","o"]

Note:

  1. 1 <= A.length <= 100
  2. 1 <= A[i].length <= 100
  3. A[i][j] is a lowercase letter

Solution:

Approach One : 先计算出A[0]字符每个字符出现的次数,然后到其余字符串去匹配,min_times为该字符在各字符串出现的最小次数, min_times = min(min_times,count(temp,A[k]));最小为0,即存在一个字符串不含有该字符,

最终min_times的取值就是该字符要放入result中的次数,解决字符重复出现的问题。

  • Time Complexity :O(n^2)
  • Space Complexity: O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
int (char c,string str)大专栏  Leetcode-Day Threean>
{
int result = 0;
for(int i = 0;i < str.size();i++)
{
if(str[i] == c)
{
result++;
}
}
return result;
}
vector<string> commonChars(vector<string>& A) {
vector<string> result;
int min_times = 0;
for(int i = 0; i < A[0].size();i++)
{
char temp = A[0][i];
bool flag = true;
min_times = 0; for(int j = 0; j < i;j++)
{
if(temp == A[0][j]) //判断该字符在前面是否出现过
{
flag = false;
}
}
if(flag) //该字符第一次出现
{
for(int h = i; h < A[0].size();h++)
{
if(A[0][h] == temp)
{
min_times++;
}
} //得到A[0][i]在第一个字符串出现的次数 times
for(int k = 1; k < A.size();k++)
{
min_times = min(min_times,count(temp,A[k]));
}
if(min_times != 0)
{
string str;
stringstream stream;
stream << temp;
str = stream.str();
for(int k = 0;k < min_times;k++)
{
result.push_back(str);
}
}
}
}
return result;
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,487
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,903
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,736
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,486
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,126
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,289