1. 程式人生 > >Java筆試題(3)

Java筆試題(3)

scan abd bst spl 輸出 rst != first adf

/**
 * 輸入:
 * 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; } }

Java筆試題(3)