fork download
  1. import java.util.*;
  2. class StringPresentTryingAllCombinationsOfB {
  3.  
  4. static int p = -1;
  5. // p is first
  6. static boolean isSubsequence(String A, String B) {
  7. int n = A.length();
  8. int m = B.length();
  9.  
  10. int i = 0, j = 0, count = 0;
  11.  
  12. while(i<n && j<m){
  13. // increment i when i get a match with char in s string
  14. // cant go ahead if no match .. order matters too so first char of g
  15. // must come before the 2nd char of g in s
  16. if(A.charAt(i)==B.charAt(j)){
  17. if(count==0){
  18. p = j;
  19. }
  20. j++;
  21. count++;
  22. }
  23. i++;
  24. }
  25.  
  26. return count == m;
  27. }
  28.  
  29. public static void main(String[] args) {
  30. Scanner sc = new Scanner(System.in);
  31.  
  32. int t = sc.nextInt();
  33.  
  34. while (t-- > 0) {
  35.  
  36. String a = sc.next();
  37. String b = sc.next();
  38.  
  39. int answer = -1;
  40.  
  41. for (int i = 1; i < b.length(); i++) {
  42.  
  43. for(char c = 'a'; c <= 'z'; c++){
  44. char[] arr = b.toCharArray();
  45. arr[i] = c;
  46. String r = new String(arr);
  47. p = -1;
  48. if(isSubsequence(a,r)){
  49. // print in 1 based indexing
  50. answer = p + 1;
  51. }
  52. }
  53. }
  54.  
  55. System.out.println(answer);
  56. }
  57.  
  58. sc.close();
  59. }
  60. }
Success #stdin #stdout 0.11s 56532KB
stdin
2
abcde
ace
xyz
yxz
stdout
1
-1