FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
leetcode-algorithms/src/FindCommonCharacters.java at master · anishLearnsToCode/leetcode-algorithms · GitHub
anishLearnsToCode
/
leetcode-algorithms
Public
Notifications
You must be signed in to change notification settings
Fork
17
Star
98
Code
Issues
0
Pull requests
0
Discussions
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Discussions
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
leetcode-algorithms
/
src
/
FindCommonCharacters.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
38 lines (35 loc) · 1.38 KB
Breadcrumbs
leetcode-algorithms
/
src
/
FindCommonCharacters.java
Copy path
File metadata and controls
38 lines (35 loc) · 1.38 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
import
java
.
util
.
ArrayList
;
import
java
.
util
.
HashMap
;
import
java
.
util
.
List
;
import
java
.
util
.
Map
;
public
class
FindCommonCharacters
{
public
List
<
String
>
commonChars
(
String
[]
words
) {
Map
<
Character
,
Integer
>
commonChars
=
getCharsFrequency
(
words
[
0
]);
Map
<
Character
,
Integer
>
wordChars
;
for
(
int
i
=
1
;
i
<
words
.
length
;
i
++) {
wordChars
=
getCharsFrequency
(
words
[
i
]);
for
(
char
letter
:
commonChars
.
keySet
()) {
commonChars
.
put
(
letter
,
Math
.
min
(
commonChars
.
get
(
letter
),
wordChars
.
getOrDefault
(
letter
,
0
)));
}
}
return
toList
(
commonChars
);
}
private
List
<
String
>
toList
(
Map
<
Character
,
Integer
>
characters
) {
List
<
String
>
result
=
new
ArrayList
<>();
for
(
Map
.
Entry
<
Character
,
Integer
>
entry
:
characters
.
entrySet
()) {
if
(
entry
.
getValue
() >
0
) {
for
(
int
i
=
0
;
i
<
entry
.
getValue
() ;
i
++)
result
.
add
(
entry
.
getKey
() +
""
);
}
}
return
result
;
}
private
Map
<
Character
,
Integer
>
getCharsFrequency
(
String
string
) {
Map
<
Character
,
Integer
>
result
=
new
HashMap
<>();
char
character
;
for
(
int
index
=
0
;
index
<
string
.
length
() ;
index
++) {
character
=
string
.
charAt
(
index
);
result
.
put
(
character
,
result
.
getOrDefault
(
character
,
0
) +
1
);
}
return
result
;
}
}
Back
|
FazBrowse Home
|
New Git URL