fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. // your code goes here
  13. }
  14. }
  15.  
  16. class Solution {
  17.  
  18. public List<String> commonChars(String[] words) {
  19. int wordsSize = words.length;
  20. int[] commonCharacterCounts = new int[26];
  21. int[] currentCharacterCounts = new int[26];
  22. List<String> result = new ArrayList<>();
  23.  
  24. // Initialize commonCharacterCounts with the characters from the first
  25. // word
  26. for (char ch : words[0].toCharArray()) {
  27. commonCharacterCounts[ch - 'a']++;
  28. }
  29.  
  30. for (int i = 1; i < wordsSize; i++) {
  31. Arrays.fill(currentCharacterCounts, 0);
  32.  
  33. // Count characters in the current word
  34. for (char ch : words[i].toCharArray()) {
  35. currentCharacterCounts[ch - 'a']++;
  36. }
  37.  
  38. // Update the common character counts to keep the minimum counts
  39. for (int letter = 0; letter < 26; letter++) {
  40. commonCharacterCounts[letter] = Math.min(
  41. commonCharacterCounts[letter],
  42. currentCharacterCounts[letter]
  43. );
  44. }
  45. }
  46.  
  47. // Collect the common characters based on the final counts
  48. for (int letter = 0; letter < 26; letter++) {
  49. for (
  50. int commonCount = 0;
  51. commonCount < commonCharacterCounts[letter];
  52. commonCount++
  53. ) {
  54. result.add(String.valueOf((char) (letter + 'a')));
  55. }
  56. }
  57.  
  58. return result;
  59. }
  60. }
Success #stdin #stdout 0.12s 52628KB
stdin
Standard input is empty
stdout
Standard output is empty