码迷,mamicode.com
首页 > 编程语言 > 详细

Java笔试题(3)

时间:2018-09-22 00:52:24      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:逆序   次数   pop   空格   输出   turn   new   system   int   

/**
 * 输入:
 * 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)

标签:逆序   次数   pop   空格   输出   turn   new   system   int   

原文地址:https://www.cnblogs.com/myibu/p/9688689.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!