Home > Mobile >  I want to check substring from last to first. How can I fix my code?
I want to check substring from last to first. How can I fix my code?

Time:04-24

I want to check if pattern is substring of s, But I want to check it from last to first index. For Example

s="Hello How Are you";

pattern="Are"

and it returns the index of e->12. because from last to first in pattern string we first see letter e.

in the below, I take my code. How can I fix it?

class Main {
    static int find(String s1, String s2) {
        int M = s1.length();
        int N = s2.length();

        for (int i = N - 1; i >= 0; i--) {

            int j;
            for (j = M - 1; j >= 0; j--)
                if (s2.charAt(i) != s1.charAt(j))
                    break;

            if (j == 0)
                return i;
        }

        return -1;

    }
    public static void main(String args[]) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please Enter first String: ");
        String s = scanner.nextLine();
        System.out.println("Please Enter Pattern String: ");
        String pat = scanner.nextLine();
        int res = find(pat, s);

        if (res == -1)
            System.out.println(res);
        else
            System.out.println("Present at index "   res);
    }
}

CodePudding user response:

Note that when you iterate over the pattern, you should also maintain some iteration on the substring of the "first string", such that you compare each letter in the pattern to the relevant letter in the substring. Something like that:

  static int find(String s1, String s2) {
    int M = s1.length();
    int N = s2.length();


    for (int i = N-1; i >=0; i--) {


      int j;
      int k = i;
      for (j = M-1; j >0; j--)
        if (s2.charAt(k) != s1.charAt(j))
          break;
        else
          k--;


      if(j==0)
        return k   (M-1);
    }

    return -1;


  } 

CodePudding user response:

Since you are using java, there is a simpler way.

public class Main {
    
    static int find(String s1, String s2) {
        return s1.lastIndexOf(s2) s2.length()-1;
    }

    public static void main(String[] args) {
            
        String str = "Hello How Are you";
        String pattern = "Are";
        
        System.out.println(find(str,pattern));
    }

}
  •  Tags:  
  • java
  • Related