File tree Expand file tree Collapse file tree 2 files changed +72
-0
lines changed Expand file tree Collapse file tree 2 files changed +72
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .andrewbayd ;
2
+
3
+ /*
4
+ Given two strings ransomNote and magazine, return true if ransomNote can be constructed from magazine and false otherwise.
5
+ Each letter in magazine can only be used once in ransomNote.
6
+
7
+ https://leetcode.com/problems/ransom-note/
8
+ */
9
+
10
+ import java .util .HashMap ;
11
+
12
+ public class RansomNote {
13
+ public boolean canConstruct (String ransomNote , String magazine ) {
14
+ HashMap <Character , Integer > map = new HashMap <>();
15
+ for (char c : magazine .toCharArray ()) {
16
+ map .put (c , map .getOrDefault (c , 0 ) + 1 );
17
+ }
18
+ for (char c : ransomNote .toCharArray ()) {
19
+ if (map .containsKey (c ) && map .get (c ) > 0 ) {
20
+ map .put (c , map .get (c ) - 1 );
21
+ } else {
22
+ return false ;
23
+ }
24
+ }
25
+ return true ;
26
+ }
27
+
28
+ public static void main (String [] args ) {
29
+ RansomNote note = new RansomNote ();
30
+ System .out .println (note .canConstruct ("a" , "b" )); //-> false
31
+ System .out .println (note .canConstruct ("aa" , "ab" )); //-> false
32
+ System .out .println (note .canConstruct ("aa" , "abba" )); //-> true
33
+ }
34
+ }
Original file line number Diff line number Diff line change
1
+ package com .andrewbayd ;
2
+
3
+ /*
4
+ Given a signed 32-bit integer x, return x with its digits reversed.
5
+ If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
6
+ Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
7
+
8
+ https://leetcode.com/problems/reverse-integer/
9
+ */
10
+
11
+ public class ReverseInteger {
12
+ public static int reverse (int x ) {
13
+ if (x == 0 ) {
14
+ return 0 ;
15
+ }
16
+
17
+ int res = 0 ;
18
+ while (x != 0 ) {
19
+ int last = x % 10 ;
20
+ x /= 10 ;
21
+ if (res > Integer .MAX_VALUE / 10
22
+ || res < Integer .MIN_VALUE / 10
23
+ || res == Integer .MAX_VALUE / 10 && last > 7
24
+ || res == Integer .MIN_VALUE / 10 && last < -8 ) {
25
+ return 0 ;
26
+ }
27
+ res = res * 10 + last ;
28
+ }
29
+ return res ;
30
+ }
31
+
32
+ public static void main (String [] args ) {
33
+ System .out .println (reverse (123 )); //-> 321
34
+ System .out .println (reverse (-321 )); //-> -123
35
+ System .out .println (reverse (1463847412 )); //-> 2147483641
36
+ System .out .println (reverse (1563847412 )); //-> 0
37
+ }
38
+ }
You can’t perform that action at this time.
0 commit comments