From 0a9b81ece8385ebdf797968606371e2692f699bf Mon Sep 17 00:00:00 2001 From: brendon <36212954+brendonmiranda@users.noreply.github.com> Date: Wed, 9 Oct 2024 11:39:09 +0100 Subject: [PATCH] amazon review score --- src/main/java/aws/AmazonReviewScore.java | 82 ++++++++++++++++++++ src/test/java/aws/AmazonReviewScoreTest.java | 17 ++++ 2 files changed, 99 insertions(+) create mode 100644 src/main/java/aws/AmazonReviewScore.java create mode 100644 src/test/java/aws/AmazonReviewScoreTest.java diff --git a/src/main/java/aws/AmazonReviewScore.java b/src/main/java/aws/AmazonReviewScore.java new file mode 100644 index 0000000..b4e340a --- /dev/null +++ b/src/main/java/aws/AmazonReviewScore.java @@ -0,0 +1,82 @@ +package aws; + +public class AmazonReviewScore { + + private class Trie { + Trie[] alpha = new Trie[26]; + boolean leaf; + } + + public int amazonReviewScore(String review, String[] prohibitedWords) { + + final Trie root = new Trie(); + for (String prohibitedWord : prohibitedWords) { + + insert(root, prohibitedWord); + } + + int max = 0; + for (int i = 0; i < review.length(); i++) { + + int count = 0; + Trie child = root; + for (int j = i; j < review.length(); j++) { + + int rep = review.toUpperCase().charAt(j) - 'A'; + if (child.alpha[rep] != null) { + + child = child.alpha[rep]; + + if (child.leaf) { + max = Math.max(count, max); + break; + } else { + count += 1; + } + + } else { + child = root; + if (child.alpha[rep] != null) { + // copy paste logic above + child = child.alpha[rep]; + + if (child.leaf) { + max = Math.max(count, max); + break; + } else { + count += 1; + } + // + } else { + count += 1; + } + } + max = Math.max(count, max); + } + } + + return max; + } + + private Trie insert(Trie root, String key) { + + Trie child = root; + + for (int i = 0; i < key.length(); i++) { + + int l = key.toUpperCase().charAt(i) - 'A'; + + if (child.alpha[l] == null) { + child.alpha[l] = new Trie(); + child = child.alpha[l]; + } else { + child = child.alpha[l]; + } + } + child.leaf = true; + + return root; + } + + +} diff --git a/src/test/java/aws/AmazonReviewScoreTest.java b/src/test/java/aws/AmazonReviewScoreTest.java new file mode 100644 index 0000000..d7e7a04 --- /dev/null +++ b/src/test/java/aws/AmazonReviewScoreTest.java @@ -0,0 +1,17 @@ +package aws; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class AmazonReviewScoreTest { + + @Test + public void test() { + AmazonReviewScore amazonReviewScore = new AmazonReviewScore(); + + Assertions.assertEquals(15, amazonReviewScore.amazonReviewScore("GoodProductButScrapAfterWash", new String[]{"crap", "odpro"})); + Assertions.assertEquals(11, amazonReviewScore.amazonReviewScore("FastDeliveryOkayProduct", new String[]{"eryoka", "yo", "eli"})); + Assertions.assertEquals(20, amazonReviewScore.amazonReviewScore("ExtremeValueForMoney", new String[]{"tuper", "douche"})); + } + +}