Java笔试题(3)

/**
 * 输入:
 * safab qeabd abdfe            (以空格隔开)
 * ab
 * 输出ab出现的次数并逆序输出含有ab的字符串
 * 输出:
 * 3
 * abdfe qeabd safab
 *
 * 输入:
 * sababa qeabad abadfe
 * aba
 * 输出:
 * 4
 * abadfe qeabad sababa
 */

import java.util.Scanner;
import java.util.Stack;

public class Main2 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String line = sc.nextLine();
        String key = sc.next();
        String[] strs = line.split(" ");
        Stack<String> stack = new Stack<String>();
        int len = strs.length;
        int result = 0;
        for(String str: strs){
            int temp = searchSubStr(str, key);
            if(0 != temp){
                stack.push(str);
                result = result+temp;
            }
        }
        System.out.println(result);
        while(!stack.empty()){
            System.out.print(stack.pop() + " ");
        }
    }
    static int searchSubStr(String str, String key){
        int count = 0;
        for (int i = 0; i < str.length(); i++) {
            int first = i;
            int from = 0;
            // 防止数组越界
            if(i<=str.length()-key.length()) {
                if (str.charAt(i) == key.charAt(from)) {
                    i++;
                    from++;
                    while (from < key.length() && str.charAt(i) == key.charAt(from)) {
                        from++;
                        i++;
                    }
                    if (from == key.length()) {
                        count++;
                    }
                }
                i = first;
            }
        }
        return count;
    }
}

猜你喜欢

转载自www.cnblogs.com/myibu/p/9688689.html