FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
Java/strings/CheckAnagrams.java at master · primary-code-test/Java · GitHub
primary-code-test
Java
Repository navigation
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
Java
/
strings
/
CheckAnagrams.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
52 lines (46 loc) · 1.33 KB
Breadcrumbs
Java
/
strings
/
CheckAnagrams.java
Copy path
File metadata and controls
52 lines (46 loc) · 1.33 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package
strings
;
import
java
.
util
.
HashMap
;
import
java
.
util
.
Map
;
/**
* Two strings are anagrams if they are made of the same letters arranged differently (ignoring the
* case).
*/
public
class
CheckAnagrams
{
public
static
void
main
(
String
[]
args
) {
assert
isAnagrams
(
"Silent"
,
"Listen"
);
assert
isAnagrams
(
"This is a string"
,
"Is this a string"
);
assert
!
isAnagrams
(
"There"
,
"Their"
);
}
/**
* Check if two strings are anagrams or not
*
* @param s1 the first string
* @param s2 the second string
* @return {@code true} if two string are anagrams, otherwise {@code false}
*/
public
static
boolean
isAnagrams
(
String
s1
,
String
s2
) {
int
l1
=
s1
.
length
();
int
l2
=
s2
.
length
();
s1
=
s1
.
toLowerCase
();
s2
=
s2
.
toLowerCase
();
Map
<
Character
,
Integer
>
charAppearances
=
new
HashMap
<>();
for
(
int
i
=
0
;
i
<
l1
;
i
++) {
char
c
=
s1
.
charAt
(
i
);
int
numOfAppearances
=
charAppearances
.
getOrDefault
(
c
,
0
);
charAppearances
.
put
(
c
,
numOfAppearances
+
1
);
}
for
(
int
i
=
0
;
i
<
l2
;
i
++) {
char
c
=
s2
.
charAt
(
i
);
if
(!
charAppearances
.
containsKey
(
c
)) {
return
false
;
}
charAppearances
.
put
(
c
,
charAppearances
.
get
(
c
) -
1
);
}
for
(
int
cnt
:
charAppearances
.
values
()) {
if
(
cnt
!=
0
) {
return
false
;
}
}
return
true
;
}
}
Back
|
FazBrowse Home
|
New Git URL