zoukankan      html  css  js  c++  java
  • NYOJ 题目5 字符串匹配

    
    

    Binary String Matching

    时间限制:3000 ms  |  内存限制:65535 KB
    难度:3
    
    
     
    
    
    描述
    Given two strings A and B, whose alphabet consist only ‘0’ and ‘1’. Your task is only to tell how many times does A appear as a substring of B? For example, the text string B is ‘1001110110’ while the pattern string A is ‘11’, you should output 3, because the pattern A appeared at the posit
    
    
     
    
    
    输入
    The first line consist only one integer N, indicates N cases follows. In each case, there are two lines, the first line gives the string A, length (A) <= 10, and the second line gives the string B, length (B) <= 1000. And it is guaranteed that B is always longer than A.
    输出
    For each case, output a single line consist a single integer, tells how many times do B appears as a substring of A.
    样例输入
    3
    11
    1001110110
    101
    110010010010001
    1010
    110100010101011 
    样例输出
    3
    0
    3 
    字符串查找有很多解法, 这里我分享下我的思路:
    	public class StringFind {
    		public static void main(String [] args) throws IOException {
    		Scanner input = new Scanner(System.in);
    			int n = input.nextInt();	
    			for(int i=0; i<n; i++) {
    				String sub = input.next();   // 要查找的子串
    				String src = input.next();   // 目标字符串
    				char[] subStr = sub.toCharArray();  
    				char[] srcStr = src.toCharArray();
    				ArrayList<Integer> list = new ArrayList<Integer>();
    				ArrayList<Integer> temp = new ArrayList<Integer>();
    				for(int j=0; j<srcStr.length-subStr.length+1; j++) { // 第一次循环次数
    					list.add(j);
    				}
    				for(int j=0; j<subStr.length; j++) {  // 总共查找次数为字串的字符数
    					//System.out.print("\n第"+j+"次:");
    					temp.clear();
    					for(int k=0; k<list.size(); k++) {
    						int pos = list.get(k);
    						if(srcStr[pos] == subStr[j]) {
    							//System.out.print(pos+" ");
    							int z = pos+1;
    							temp.add(z);  //每次的下一个字符符合, 则将该下标存入tmp 中。
    						}
    					}
    					list.clear();
    					list.addAll(temp);
    					//System.out.println("list.size(): " + list.size());
    				}
    				//System.out.print("\n 剩余: ");
    				//for(int j=0; j<list.size(); j++) {
    					//System.out.print(list.get(j)+" ");
    				//}
    				// 表中个数即父串中字串符合个数
    				System.out.println(list.size());
    			}
    		}
    	} 
    

      




  • 相关阅读:
    Linux 系统下10个查看网络与监听的命令
    Linux下用gdb 调试、查看代码堆栈
    GPIO引脚速度的应用匹配
    编写安全的代码——小心有符号数的右移操作
    C语言实现类似C++的容器vector
    求字符串长度之递归与非递归的C语言实现
    字符串拷贝函数递归与非递归的C语言实现
    WriteLogHelper
    JsonHelper
    ConfigHelper
  • 原文地址:https://www.cnblogs.com/thoupin/p/2493510.html
Copyright © 2011-2022 走看看