-
Notifications
You must be signed in to change notification settings - Fork 0
/
15_Nov_2023_Better_String.java
58 lines (49 loc) · 1.76 KB
/
15_Nov_2023_Better_String.java
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
/*
Author : Divyanshi Dixit
Date : Nov 15, 2023
Problem : Better Sting
Difficulty : Hard
Problem Link: https://www.geeksforgeeks.org/problems/better-string/1
Problem Statement: Given a pair of strings of equal lengths, Geek wants to find the better string. The better string is the string having more number of distinct subsequences.
If both the strings have equal count of distinct subsequence then return str1.
Solution Approach: TBD
*/
/* ------------CODE---------------- */
class Solution {
// Function to calculate the value for each character in the string
private static int solve(String s) {
int count = 1;
HashMap<Character, Integer> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
// If the character is not present in the map, add it with the current count value
if (!map.containsKey(s.charAt(i))) {
map.put(s.charAt(i), count);
count *= 2;
} else {
// If the character is already present, update the count value
int temp = map.get(s.charAt(i));
map.put(s.charAt(i), count);
count = count * 2 - temp;
}
}
return count;
}
// Function to compare two strings based on their calculated values
public static String betterString(String str1, String str2) {
int first = solve(str1);
int second = solve(str2);
// Compare the values and return the string with the higher value
if (first > second) {
return str1;
} else if (second > first) {
return str2;
} else {
// If both values are equal, return str1
return str1;
}
}
}
/*
Time Complexity:
Space Complexity:
*/