diff --git a/src/CountAsterisks2315.java b/src/CountAsterisks2315.java deleted file mode 100644 index 1363e59..0000000 --- a/src/CountAsterisks2315.java +++ /dev/null @@ -1,20 +0,0 @@ -public class CountAsterisks2315 { - public int countAsterisks(String s) { - String[] words = s.split("\\|"); - int res = 0; - for (int i = 0; i < words.length; i = i + 2) { - for (int j = 0; j < words[i].length(); j++) { - if (words[i].charAt(j) == '*') { - res++; - } - } - } - return res; - } - - public static void main(String[] args) { - String s = "l|*e*et|c**o|*de|"; - // 2 - System.out.println(new CountAsterisks2315().countAsterisks(s)); - } -} diff --git a/src/main/java/com/leetcode/easy/CountAsterisks2315.java b/src/main/java/com/leetcode/easy/CountAsterisks2315.java new file mode 100644 index 0000000..c395850 --- /dev/null +++ b/src/main/java/com/leetcode/easy/CountAsterisks2315.java @@ -0,0 +1,29 @@ +// Tags: String +package com.leetcode.easy; + +public class CountAsterisks2315 { + /** + * Let n = s.length() and m = words.length (the number of split segments), where m <= n + 1. + * Time complexity: O(n) + * Breakdown: + * - Split operation: s.split("\\|") iterates through the entire string - O(n) + * - Outer loop: Iterates through about half of the segments - O(m/2) = O(m) + * - Inner loop: Across all iterations, the total number of characters checked is at most n - O(n) + * Overall: O(n) + *

+ * Space complexity: O(n) + * - Array storage: String[] words holds m references to substrings whose total length is O(n) - O(n) + */ + public int countAsterisks(String s) { + String[] words = s.split("\\|"); + int res = 0; + for (int i = 0; i < words.length; i = i + 2) { + for (int j = 0; j < words[i].length(); j++) { + if (words[i].charAt(j) == '*') { + res++; + } + } + } + return res; + } +} diff --git a/src/test/java/com/leetcode/easy/CountAsterisks2315Test.java b/src/test/java/com/leetcode/easy/CountAsterisks2315Test.java new file mode 100644 index 0000000..d2129b0 --- /dev/null +++ b/src/test/java/com/leetcode/easy/CountAsterisks2315Test.java @@ -0,0 +1,42 @@ +package com.leetcode.easy; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class CountAsterisks2315Test { + private CountAsterisks2315 solution; + + @BeforeEach + void setUp() { + solution = new CountAsterisks2315(); + } + + @Test + void testCountAsterisks_Example1() { + String s = "l|*e*et|c**o|*de|"; + + int result = solution.countAsterisks(s); + + assertEquals(2, result); + } + + @Test + void testCountAsterisks_Example2() { + String s = "iamprogrammer"; + + int result = solution.countAsterisks(s); + + assertEquals(0, result); + } + + @Test + void testCountAsterisks_Example3() { + String s = "yo|uar|e**|b|e***au|tiful"; + + int result = solution.countAsterisks(s); + + assertEquals(5, result); + } +}