Profile Photo

Distinct characters in a string

Created on: Jan 16, 2025

Input : Geeks for Geeks Output : for Input : Hello Geeks Output : HoGks
import java.util.List; import java.util.stream.Collectors; public class Solution { public static List<Character> uniqueChar(String str) { return null; } public static void main(String[] args) { boolean test = true; test = test && test == uniqueChar("aabdcce").equals(List.of('b', 'd', 'e')); // Test Case 1: All unique characters test = test && uniqueChar("abcdef").equals(List.of('a', 'b', 'c', 'd', 'e', 'f')); // Test Case 2: All characters repeated test = test && uniqueChar("aabbccdd").equals(List.of()); // Test Case 3: Mixed unique and repeated characters test = test && uniqueChar("aabbcdee").equals(List.of('c', 'd')); // Test Case 4: String with spaces test = test && uniqueChar("a b c a b").equals(List.of('c')); // Test Case 5: Empty string test = test && uniqueChar("").equals(List.of()); // Test Case 6: String with a single character test = test && uniqueChar("z").equals(List.of('z')); // Test Case 7: String with special characters test = test && uniqueChar("@#@!$!").equals(List.of('#', '$')); // Test Case 8: Large string with repeated patterns String largeString = "abc".repeat(1000) + "xyz"; List<Character> expectedLarge = List.of('x', 'y', 'z'); test = test && uniqueChar(largeString).equals(expectedLarge); // Test Case 9: Unicode characters test = test && uniqueChar("a😀b😀c").equals(List.of('a', 'b', 'c')); if (test) { System.out.println("pass"); } else { System.out.println("Fail"); } } }

Solution

public static List<Character> uniqueChar(String str) { return str.chars().mapToObj(obj->(char)obj) .filter(c->str.indexOf(c)==str.lastIndexOf(c)) .collect(Collectors.toList()); }

Reference