经典算法:(整理汇总)
1)如何快速倒叙:
public static char[] reverseArray(char[] c){ char t; for(int i=0;i<c.length/2;i++){ t = c[i]; c[i] = c[c.length-1-i]; c[c.length-1-i] = t; } return c; }
2)
/**
* 编写一个截取字符串的函数,输入为一个字符串和字节数,
* 输出为按字节截取的字符串,但要保证汉字不被截取半个,
* 如“我ABC”,4,应该截取“我AB”,输入“我ABC汉DEF”,6,
* 应该输出“我ABC”,而不是“我ABC+汉的半个”。
*/
public class SubString { public static void main(String[] args) throws Exception{ String str1 ="我ABC汉"; int num =trimGBK(str1.getBytes("GBK"),5); System.out.println(str1.substring(0,num)); } //算法,返回一个数字表示截取的长度 public static int trimGBK(byte[] buf,int n){ int num = 0; boolean bChineseFirstHalf = false; for(int i=0;i<n;i++){ if(buf[i]<0&& !bChineseFirstHalf){ bChineseFirstHalf= true; }else{ num++; bChineseFirstHalf= false; } } return num; } }
3)
/**
* 有一个字符串,
* 其中包含中文字符、英文字符和数字字符,
* 请统计和打印出各个字符的个数
*/
public static void main(String[] args) { String content = "fs2爱国a4324hf年gd费合342计kjiods爱国32"; Map<Object,Object> map = new HashMap<Object,Object>(); for(int i=0;i<content.length();i++){ //获得每个key,用c表示 char c = content.charAt(i); //根据key值返回value,用num表示 Integer num = (Integer)map.get(c); if(num==null){ num=1; }else{ num+=1; } map.put(c, num); } Set<Entry<Object,Object>> entries = map.entrySet(); for(Entry<Object,Object> entry : entries){ System.out.println(entry.getKey()+ ":" + entry.getValue()); } }
4)
/**
* 如果一串字符如"aaaabbc中国1512"要分别统计英文字符的数量,
* 中文字符的数量,和数字字符的数量,
* 假设字符中没有中文字符、英文字符、数字字符之外的其他特殊字符
*/
public static void main(String[] args) { String str = "aa36法搜89aav大bbc中国15啥12"; int englishChar = 0; int chineseChar = 0; int digitalChar = 0; for(int i=0;i<str.length();i++){ char c = str.charAt(i); if((c>='a'&&c<='z')||(c>='A'&&c<='Z')){ englishChar++; }else if(c>='0'&&c<='9'){ digitalChar++; }else{ chineseChar++; } } System.out.println("该字符串中英文字符个数是:"+englishChar+"" + "个;数字字符个数是:"+digitalChar+"个;" + "中文字符个数是:"+chineseChar+"个"); }
5)快速查重
public static void main(String[] args) throws Exception { int[] list=new int[1000000]; int i = 0; for (;i<list.length;i++) { list[i]=i; } //设置一个重复的数,使第600000个数和第90000个数是均为90000 list[600000]=90000; Set set = new HashSet(); for( i=0;i<list.length;i++){ //利用set的add方法,如果已经存在,则返回false if(!set.add(list[i])) break; } System.out.println("the same number is "+list[i]); }
6)统计字符串中“中国”个数
解一:前后加空格,使用split
public static void main(String[] args) { String str = "中国的说法中国人家的废旧发丝啊发哈U盾和综合哦啊过后中国fo" + "adsjfidsojoafsjjfsadzhonga哈哈发中国孤" + "粉丝大呼覅护肤is傲中国"; str = " "+str+" ";//前后各加一个空格 System.out.println(str.split("中国").length-1); }
解二:
public static void main(String[] args) { String str=("中国dfghds中佛挡杀佛国hfrtdhg中国ffdhfdhhtfnx中国sadgh中国上"); int a = str.length()-str.replaceAll("中国", "").length(); System.out.println(a/2); }