Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions src/main/java/g0401_0500/s0468_validate_ip_address/Solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package g0401_0500.s0468_validate_ip_address;

// #Medium #String

public class Solution {
private static final String NEITHER = "Neither";

public String validIPAddress(String ip) {
if (ip.length() == 0) {
return NEITHER;
}
String[] arr = ip.split("\\.", -1);
String[] arr1 = ip.split(":", -1);
if (arr.length == 4) {
for (String num : arr) {
try {
if ((num.length() > 1 && num.startsWith("0")) || Integer.parseInt(num) > 255) {
return NEITHER;
}
} catch (Exception e) {
return NEITHER;
}
}
return "IPv4";
} else if (arr1.length == 8) {
for (String num : arr1) {
if (num.length() < 1 || num.length() > 4) {
return NEITHER;
}
for (int j = 0; j < num.length(); j++) {
char ch = num.charAt(j);
if (ch > 9) {
if (Character.isLowerCase(ch) && ch > 'f') {
return NEITHER;
} else if (Character.isUpperCase(ch) && ch > 'F') {
return NEITHER;
}
}
}
}
return "IPv6";
}
return NEITHER;
}
}
43 changes: 43 additions & 0 deletions src/main/java/g0401_0500/s0468_validate_ip_address/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
468\. Validate IP Address

Medium

Given a string `queryIP`, return `"IPv4"` if IP is a valid IPv4 address, `"IPv6"` if IP is a valid IPv6 address or `"Neither"` if IP is not a correct IP of any type.

**A valid IPv4** address is an IP in the form <code>"x<sub>1</sub>.x<sub>2</sub>.x<sub>3</sub>.x<sub>4</sub>"</code> where <code>0 <= x<sub>i</sub> <= 255</code> and <code>x<sub>i</sub></code> **cannot contain** leading zeros. For example, `"192.168.1.1"` and `"192.168.1.0"` are valid IPv4 addresses but `"192.168.01.1"`, while `"192.168.1.00"` and `"192.168@1.1"` are invalid IPv4 addresses.

**A valid IPv6** address is an IP in the form <code>"x<sub>1</sub>:x<sub>2</sub>:x<sub>3</sub>:x<sub>4</sub>:x<sub>5</sub>:x<sub>6</sub>:x<sub>7</sub>:x<sub>8</sub>"</code> where:

* <code>1 <= x<sub>i</sub>.length <= 4</code>
* <code>x<sub>i</sub></code> is a **hexadecimal string** which may contain digits, lower-case English letter (`'a'` to `'f'`) and upper-case English letters (`'A'` to `'F'`).
* Leading zeros are allowed in <code>x<sub>i</sub></code>.

For example, "`2001:0db8:85a3:0000:0000:8a2e:0370:7334"` and "`2001:db8:85a3:0:0:8A2E:0370:7334"` are valid IPv6 addresses, while "`2001:0db8:85a3::8A2E:037j:7334"` and "`02001:0db8:85a3:0000:0000:8a2e:0370:7334"` are invalid IPv6 addresses.

**Example 1:**

**Input:** queryIP = "172.16.254.1"

**Output:** "IPv4"

**Explanation:** This is a valid IPv4 address, return "IPv4".

**Example 2:**

**Input:** queryIP = "2001:0db8:85a3:0:0:8A2E:0370:7334"

**Output:** "IPv6"

**Explanation:** This is a valid IPv6 address, return "IPv6".

**Example 3:**

**Input:** queryIP = "256.256.256.256"

**Output:** "Neither"

**Explanation:** This is neither a IPv4 address nor a IPv6 address.

**Constraints:**

* `queryIP` consists only of English letters, digits and the characters `'.'` and `':'`.
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package g0401_0500.s0470_implement_rand10_using_rand7;

// #Medium #Math #Randomized #Probability_and_Statistics #Rejection_Sampling

import java.security.SecureRandom;

public class Solution {
private final SecureRandom secureRandom = new SecureRandom();

public int rand10() {
int num = (rand7() - 1) * 7 + rand7();
if (num <= 40) {
return (num % 10) + 1;
}
num = num - 40;
num = (rand7() - 1) * 9 + num;
if (num <= 60) {
return (num % 10) + 1;
}
num = num - 60;
int res;
do {
res = (rand7() + 1) * 3 + num;
} while (res <= 20);
return (res % 10) + 1;
}

private int rand7() {
return secureRandom.nextInt(7) + 1;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
470\. Implement Rand10() Using Rand7()

Medium

Given the **API** `rand7()` that generates a uniform random integer in the range `[1, 7]`, write a function `rand10()` that generates a uniform random integer in the range `[1, 10]`. You can only call the API `rand7()`, and you shouldn't call any other API. Please **do not** use a language's built-in random API.

Each test case will have one **internal** argument `n`, the number of times that your implemented function `rand10()` will be called while testing. Note that this is **not an argument** passed to `rand10()`.

**Example 1:**

**Input:** n = 1

**Output:** [2]

**Example 2:**

**Input:** n = 2

**Output:** [2,8]

**Example 3:**

**Input:** n = 3

**Output:** [3,8,10]

**Constraints:**

* <code>1 <= n <= 10<sup>5</sup></code>

**Follow up:**

* What is the [expected value](https://en.wikipedia.org/wiki/Expected_value) for the number of calls to `rand7()` function?
* Could you minimize the number of calls to `rand7()`?
62 changes: 62 additions & 0 deletions src/main/java/g0401_0500/s0472_concatenated_words/Solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package g0401_0500.s0472_concatenated_words;

// #Hard #Array #String #Dynamic_Programming #Depth_First_Search #Trie

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution {
private final List<String> ans = new ArrayList<>();
private Trie root;

public List<String> findAllConcatenatedWordsInADict(String[] words) {
root = new Trie();
Arrays.sort(words, (a, b) -> Integer.compare(a.length(), b.length()));
for (String word : words) {
Trie ptr = root;
if (search(word, 0, 0)) {
ans.add(word);
} else {
for (int j = 0; j < word.length(); j++) {
if (ptr.nxt[word.charAt(j) - 'a'] == null) {
ptr.nxt[word.charAt(j) - 'a'] = new Trie();
}
ptr = ptr.nxt[word.charAt(j) - 'a'];
}
ptr.endHere = true;
}
}
return ans;
}

private boolean search(String cur, int idx, int wordCnt) {
if (idx == cur.length()) {
return wordCnt >= 2;
}
Trie ptr = root;
for (int i = idx; i < cur.length(); i++) {
if (ptr.nxt[cur.charAt(i) - 'a'] == null) {
return false;
}
if (ptr.nxt[cur.charAt(i) - 'a'].endHere) {
boolean ret = search(cur, i + 1, wordCnt + 1);
if (ret) {
return true;
}
}
ptr = ptr.nxt[cur.charAt(i) - 'a'];
}
return ptr.endHere && wordCnt >= 2;
}

private static class Trie {
Trie[] nxt;
boolean endHere;

Trie() {
nxt = new Trie[26];
endHere = false;
}
}
}
28 changes: 28 additions & 0 deletions src/main/java/g0401_0500/s0472_concatenated_words/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
472\. Concatenated Words

Hard

Given an array of strings `words` (**without duplicates**), return _all the **concatenated words** in the given list of_ `words`.

A **concatenated word** is defined as a string that is comprised entirely of at least two shorter words in the given array.

**Example 1:**

**Input:** words = ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"]

**Output:** ["catsdogcats","dogcatsdog","ratcatdogcat"]

**Explanation:** "catsdogcats" can be concatenated by "cats", "dog" and "cats"; "dogcatsdog" can be concatenated by "dog", "cats" and "dog"; "ratcatdogcat" can be concatenated by "rat", "cat", "dog" and "cat".

**Example 2:**

**Input:** words = ["cat","dog","catdog"]

**Output:** ["catdog"]

**Constraints:**

* <code>1 <= words.length <= 10<sup>4</sup></code>
* `0 <= words[i].length <= 1000`
* `words[i]` consists of only lowercase English letters.
* <code>0 <= sum(words[i].length) <= 10<sup>5</sup></code>
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package g0401_0500.s0468_validate_ip_address;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

import org.junit.jupiter.api.Test;

class SolutionTest {
@Test
void validIPAddress() {
assertThat(new Solution().validIPAddress("172.16.254.1"), equalTo("IPv4"));
}

@Test
void validIPAddress2() {
assertThat(
new Solution().validIPAddress("2001:0db8:85a3:0:0:8A2E:0370:7334"),
equalTo("IPv6"));
}

@Test
void validIPAddress3() {
assertThat(new Solution().validIPAddress("256.256.256.256"), equalTo("Neither"));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package g0401_0500.s0470_implement_rand10_using_rand7;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

import org.junit.jupiter.api.Test;

class SolutionTest {
@Test
void rand10() {
for (int i = 0; i < 1; i++) {
int result = new Solution().rand10();
assertThat(result >= 1 && result <= 10, equalTo(true));
}
}

@Test
void rand102() {
for (int i = 0; i < 2; i++) {
int result = new Solution().rand10();
assertThat(result >= 1 && result <= 10, equalTo(true));
}
}

@Test
void rand103() {
for (int i = 0; i < 3; i++) {
int result = new Solution().rand10();
assertThat(result >= 1 && result <= 10, equalTo(true));
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package g0401_0500.s0472_concatenated_words;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

import java.util.ArrayList;
import java.util.Arrays;
import org.junit.jupiter.api.Test;

class SolutionTest {
@Test
void findAllConcatenatedWordsInADict() {
assertThat(
new Solution()
.findAllConcatenatedWordsInADict(
new String[] {
"cat",
"cats",
"catsdogcats",
"dog",
"dogcatsdog",
"hippopotamuses",
"rat",
"ratcatdogcat"
}),
equalTo(
new ArrayList<>(
Arrays.asList("dogcatsdog", "catsdogcats", "ratcatdogcat"))));
}

@Test
void findAllConcatenatedWordsInADict2() {
assertThat(
new Solution()
.findAllConcatenatedWordsInADict(new String[] {"cat", "dog", "catdog"}),
equalTo(new ArrayList<>(Arrays.asList("catdog"))));
}
}