https://www.nowcoder.com/practice/ac18db43a404459da9c72e8aa1816f80?tpId=85&tqId=29874&tPage=1&rp=1&ru=/ta/2017test&qru=/ta/2017test/question-ranking
public class Main{
public String Solution(String s, String s1, String s2){
int flag1 = 0, flag2 = 0;
int from = hasString(s,s1,0);
int hasIt = hasString(s,s2,from);
if(hasIt!=-1) flag1 = 1;
s = new StringBuilder(s).reverse().toString();
from = hasString(s,s1,0);
hasIt = hasString(s,s2,from);
if(hasIt!=-1) flag2 = 1;
if(flag1==1&&flag2==1) return "both";
else if(flag1==1) return "forward";
else if(flag2==1) return "backward";
else return "invalid";
}
// 从s的第fromIndex开始找,返回剩余子串的首位索引
public int hasString(String s, String s1, int fromIndex){
if(fromIndex>=s.length()) return -1;
int N = s1.length();
int[] next = getNext(s1);
int i = fromIndex, j=0;
while(i<s.length() && j<N){
if(s.getCharAt(i)==s.getCharAt(j)){
i++;
j++;
}
else{
j = next[j];
}
}
if(j == N) return i;
return -1;
}
public int[] getNext(String s){
int N = s.length();
int[] next = new int[N];
next[0] = -1;
k=-1;
j=0;
while(j<N-1){
if(k==-1 || s.getCharAt(j)==s.getCharAt(k)){
j++;
k++;
next[j] = k;
}
else{
k = next[k];
}
}
return next;
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
Main ob = new Main();
while(in.hasNextLine()){
String s = in.nextLine();
String s1 = in.nextLine();
String s2 = in.nextLine();
System.out.println(ob.Solution(s,s1,s2));
}
}
}