zoukankan      html  css  js  c++  java
  • Java实现统计某字符串在另一个字符串中出现的次数

    面试时会经常考这样的题目,估计也不让使用正则表达式。还好这个算法还算简单,不过在草稿纸上写难免会出现运行异常,好吧,面试官赢了,乃们屌丝就实实在在的把代码码出来吧。

    谢谢“心扉”对我代码bug的纠正,现已想到更简便的方法,思路就是从被匹配字符串a中一个一个往后推,截取b字符串长度的字符串:

    public class CountHit {
    	public static void main(String[] args) {
    		String a = "123456abcde6a6abc6ab";
    		String b = "6abc";
    		System.out.println(new CountHit().hit(a, b));
    	}
    
    	/**
    	 * 
    	 * @param a
    	 *            被匹配的长字符串
    	 * @param b
    	 *            匹配的短字符串
    	 * @return 匹配次数
    	 */
    	public int hit(String a, String b) {
    		if (a.length() < b.length()) {
    			return 0;
    		}
    		char[] a_t = a.toCharArray();
    		int count = 0;
    
    		for (int i = 0; i < a.length() - b.length(); i++) {
    			StringBuffer buffer = new StringBuffer();
    			for (int j = 0; j < b.length(); j++) {
    				buffer.append(a_t[i + j]);
    			}
    			if(buffer.toString().equals(b)){
    				count ++;
    			}
    		}
    
    		return count;
    	}
    }
    

    下面这个算法有bug,临界点是部分匹配时会导致接下来后续真正能匹配的字符串被跳过一个字符,求高手纠正:

    /**
     * 统计某字符串在另一个字符串中出现的次数
     * 
     * 
     */
    public class CountHit {
    	public static void main(String[] args) {
    		String a = "123456abcde6ab";
    		String b = "6abc";
    		System.out.println(new CountHit().hit(a, b));
    	}
    
    	/**
    	 * 
    	 * @param a
    	 *            被匹配的长字符串
    	 * @param b
    	 *            匹配的短字符串
    	 * @return 匹配次数
    	 */
    	public int hit(String a, String b) {
    		if (a.length() < b.length()) {
    			return 0;
    		}
    		char[] a_t = a.toCharArray();
    		char[] b_t = b.toCharArray();
    		int count = 0, temp = 0, j = 0;
    
    		for (int i = 0; i < a_t.length; i++) {
    			// 保证一个连续的字符串 b 跟 a中某段相匹配
    			if (a_t[i] == b_t[j] && j < b_t.length) {
    				temp++;
    				j++;
    				// 此时连续的字符串 b 跟 已跟 a 中某段相匹配
    				if (temp == b_t.length) {
    					count++;
    					temp = 0;
    					j = 0;
    				}
    			}
    			// 只要有一个字符不匹配,temp计数从来
    			else {
    				temp = 0;
    				j = 0;
    			}
    		}
    
    		return count;
    	}
    }
    
  • 相关阅读:
    Google开源单元測试框架Google Test:VS2012 配置
    ubuntu16.04 uninstall cuda 9.0 completely and install 8.0 instead
    ubuntu 16.04 安装cuda的方法
    ubuntu垃圾文件清理方法
    行人检测资源(下)代码数据
    行人检测资源(上)综述文献
    开源深度学习架构Caffe
    python pip 安装库文件报错:pip install ImportError: No module named _internal
    Canny算子
    vmware中nat模式中使用静态ip后无法上网的问题
  • 原文地址:https://www.cnblogs.com/forchase/p/4082443.html
Copyright © 2011-2022 走看看