fork download
  1.  
  2. import java.util.ArrayList;
  3. import java.util.Arrays;
  4. import java.util.List;
  5.  
  6. class Main {
  7. public List<Integer> matchingCnt(int n, List<String> X) {
  8. int[][] g=new int[n][27];
  9. // n positions since any string can be any length and 26 characters
  10. // since abc and adb both have a at pos 0 then it can be counted
  11. //so at the 0th j position we have count of 1 for a position .. also at 0 so g[0][0]=1
  12. List<Integer> res=new ArrayList<>();
  13. for( int i=0;i<n;i++){
  14. res.add(0);
  15. }
  16. // time is n*d where d is max length of string .. so time is O(N)
  17. // space is O(26*N)~O(N)
  18. for(int i=n-1;i>=0;i--){
  19. String s=X.get(i);
  20. int d=s.length();
  21. int c=0;
  22. for(int j = 0; j < d; j++){
  23. int x = s.charAt(j)-'a';
  24. c+=g[i][x];
  25. g[i][x]++;
  26. }
  27. res.set(i,c);
  28. }
  29. return new ArrayList<>();
  30. }
  31. public static void main(String[] args) {
  32. Main sol = new Main();
  33. int n = 3;
  34. List<String> X = Arrays.asList("abc", "ade", "abc");
  35. List<Integer> result = sol.matchingCnt(n, X);
  36.  
  37. for (int i : result) {
  38. System.out.print(i + " ");
  39. }
  40. }
  41. }
  42.  
Success #stdin #stdout 0.08s 54568KB
stdin
Standard input is empty
stdout
Standard output is empty