【面试】刷题

https://www.nowcoder.com/practice/ac18db43a404459da9c72e8aa1816f80?tpId=85&tqId=29874&tPage=1&rp=1&ru=/ta/2017test&qru=/ta/2017test/question-ranking


import java.util.*;


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));
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值