• 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());
    			}
    		}
    	} 
    

      




  • 相关阅读:
    ASP.NET MVC请求处理管道生命周期的19个关键环节(13-19)
    ASP.NET MVC请求处理管道生命周期的19个关键环节(7-12)
    ASP.NET MVC请求处理管道生命周期的19个关键环节(1-6)
    关于领域模型
    WebForm和MVC的一些知识(转)
    抽象工厂
    SCP,scp linux2台机器之间如何传输文件
    mysql卸载(windows)【转】
    (5.2.3)配置服务器参数——服务器性能估算
    Windows命令行使用FTP
  • 原文地址:https://www.cnblogs.com/thoupin/p/2493510.html
Copyright © 2020-2023  润新知