【原创】由一道面试题说起

一个字符串参数(value)由字母(a-z,A-Z)组成,且最大字符位数为40,要求写一个函数(maxLength)返回该参数中连续相同字母的最大个数及该字母,如果最大位数有多个,则返回第一个。例:字符串“aaaddxxxxddddxxxx”,返回值为:“x,4”。
要求:请考虑代码执行的效率并注意编码的风格

 

 

 package com.fish.codesample; public class TimeTracker { private long startTime; public TimeTracker() { startTime = System.nanoTime(); } public void reSet(){ startTime = System.nanoTime(); } public void printTime(){ long consumingTime = System.nanoTime() - startTime; System.out.println("Total Time consuming : " + consumingTime); } } package com.fish.codesample; public class FindMaxCharsSample{ public static void main(String[] args){ TimeTracker tt = new TimeTracker(); String content = "aaaddxxxxddddxxxx"; findMaxLengthCharsOne(content); tt.printTime(); tt.reSet(); findMaxLengthCharsTwo(content); tt.printTime(); } private static void findMaxLengthCharsOne(String content) { int max = 0; String result = null; String after = null; int count = 0; while(content.length() != 0){ after = content.replaceAll("^(//w)//1*",""); count = content.length() - after.length(); if(count > max){ max = count; result = content.substring(0,1); } content = after; } System.out.println(result + " , " + max); } private static void findMaxLengthCharsTwo(String content) { char[] contentChars = content.toCharArray(); int length = contentChars.length; int max = 0; int posIndex = 0; int temp = 1; for(int i=1; i<length; i="" if="" contentchars="" temp="" else="" temp="1;" if=""> max){ max = temp; posIndex = i; } } System.out.println(contentChars[posIndex] + " , " + max); } } </length;>

 

Output Result as following:
x , 4
Total Time consuming : 1313574
x , 4
Total Time consuming : 54197

 

效率显然是第二种方法更高一些

 

你可能感兴趣的:(String,面试,null,Class,output)