Skip to content

Commit b55a16a

Browse files
committed
String Scramble
1 parent b164ada commit b55a16a

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

src/medium/StringScramble.java

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package medium;
2+
3+
import java.util.HashMap;
4+
5+
/**
6+
* Have the function StringScramble(str1,str2) take both parameters
7+
* being passed and return the string true. if a portion of str1 characters
8+
* can be rearranged to match str2, otherwise return the string false.
9+
* For example: if str1 is "rkqodlw" and str2 is "world"
10+
* the output should return true.
11+
* Punctuation and symbols will not be entered with the parameters.
12+
*/
13+
public class StringScramble {
14+
15+
/**
16+
* String Scramble function.
17+
*
18+
* @param str1 input string 1
19+
* @param str2 input string 2
20+
* @return "true" if rearranged string matches input string 2
21+
*/
22+
private static String stringScramble(String str1, String str2) {
23+
HashMap<String, Integer> freq = new HashMap<>();
24+
String[] arr1 = str1.replaceAll("([^" + str2 + "])", "").split("");
25+
String[] arr2 = str2.split("");
26+
for (String letter : arr1) {
27+
if (freq.containsKey(letter)) {
28+
freq.put(letter, freq.get(letter) + 1);
29+
} else {
30+
freq.put(letter, 1);
31+
}
32+
}
33+
for (String letter : arr2) {
34+
if (freq.containsKey(letter) && freq.get(letter) > 0) {
35+
freq.put(letter, freq.get(letter) - 1);
36+
} else {
37+
return "false";
38+
}
39+
}
40+
return "true";
41+
}
42+
43+
/**
44+
* Entry point.
45+
*
46+
* @param args command line arguments
47+
*/
48+
public static void main(String[] args) {
49+
String result1 = stringScramble("win33er", "winner");
50+
System.out.println(result1);
51+
String result2 = stringScramble("rkqodlw", "world");
52+
System.out.println(result2);
53+
}
54+
55+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy