2020年华为笔试题

题目

  分别输入两个非空字符串,第一个字符串可能包含tab键、回车键,第二个字符串则不包含,求第一个字符串中(忽略tab键回车键)第二个字符串出现的个数,第一个字符串中连续有两个字符串符合条件时都计入计数个数。

 如:

   输入

     第一个字符串:abb  bd

     第二个字符串:bb

   输出

     2

 1 import java.util.*;
 2 import java.util.regex.Matcher;
 3 import java.util.regex.Pattern;
 4 
 5 public class Main {
 6     public static void main(String[] args) {
 7         Scanner scanner = new Scanner(System.in);
 8         while (scanner.hasNext()) {
 9             String firstStr = scanner.nextLine();
10             /*
11             * 去除第一个字符串中的空格和回车
12             * \n 回车(\u000a)
13             *  \s 空格(\u0008)
14             *
15             * */
16             Pattern p = Pattern.compile("\\s*|\n");
17             Matcher m = p.matcher(firstStr);
18             firstStr = m.replaceAll("");
19             String secondStr = scanner.nextLine();
20             if(firstStr.length()< secondStr.length()){
21                 System.out.println(0);
22                 break;
23             }
24             int count = 0;
25             while (firstStr.length() >= secondStr.length()){
26                 String temp = firstStr.substring(0,secondStr.length());
27                     if(temp.equals(secondStr)){
28                         count ++;
29                         firstStr = firstStr.substring(1,firstStr.length());
30                     }else {
31                         firstStr = firstStr.substring(1,firstStr.length());
32                     }
33             }
34             System.out.println(count);
35         }
36     }
37 }
扫描二维码关注公众号,回复: 9886645 查看本文章

===欢迎吐槽。。。

猜你喜欢

转载自www.cnblogs.com/tombky/p/12509067.html