您的位置:首页 > 职场人生

我面试的几道算法题

2010-09-15 10:39 399 查看
1.输入如下字符串3a/4b/5c,通过处理输出aaa/bbbb/ccccc

/**
*3a/4b/5c
*aaa/bbbb/ccccc
* @param str
* @return
*/
public static String reverseString(String str){
String[]arrstr = str.split("/");
StringBuffer sb = new StringBuffer();
for(int i = 0; i < arrstr.length; i++){
if(arrstr[i].length() == 1){
sb.append(arrstr[i]);
}else{
String num = arrstr[i].substring(0, 1);
String str2 = arrstr[i].substring(1,2);
if(Pattern.compile("^//d{1}$").matcher(num).matches()){
int num2 = Integer.parseInt(num);
for(int j = 0; j<num2; j++){
sb.append(str2);
}
}else{
sb.append(arrstr[i]);
}
}
if(!( i == (arrstr.length -1))){
sb.append("/");
}
}
System.out.println("字符串/'"+str+"/':被转换成了如下字符串:");
return sb.toString();
}

2..输入如下字符串aaa/bbbb/ccccc,通过处理输出3a/4b/5c

/**
*aaa/bbbb/ccccc
* 3a/4b/5c
* @param str
* @return
*/
public static String reverseString2(String str){
String[] arrstr = str.split("/");
StringBuffer sb = new StringBuffer();
for(int i = 0; i < arrstr.length; i++){
if(arrstr[i].length() == 1)
sb.append(arrstr[i]);
else{
String char2 = arrstr[i].substring(1, 2);
sb.append(""+arrstr[i].length()+""+char2);
}
if(!( i == (arrstr.length -1))){
sb.append("/");
}
}

System.out.println("字符串/'"+str+"/':被转换成了如下字符串:");
return sb.toString();
}

3.写一个文件搜索方法实现对某个指定磁盘的文件搜索

public static void dir(File file) throws IOException{

File[] allFile = null;

if(file.isDirectory()){
allFile = file.listFiles();

for(int i =0; i < allFile.length; i++){
if(!allFile[i].isDirectory()){

String fileName = allFile[i].getName();
String extension = fileName.substring(fileName.lastIndexOf("."), fileName.length());
System.out.println("文件:"+fileName+"--------的后缀名是:"+"/'"+extension+"/'");
if(extension.equals(".txt")){
FileInputStream inputStream = new FileInputStream(allFile[i]);
File f = new File("e://test.txt");

FileOutputStream outputStream = new FileOutputStream("e://test.txt");
BufferedOutputStream bout = new BufferedOutputStream(outputStream);
byte[] bs = new byte[1024];
int index = -1;
while((index = inputStream.read(bs)) != -1){
outputStream.write(bs, 0, index);
}
}
}else{
//递归
dir(allFile[i]);
}
}

}else{
System.out.println(file.getName());
}

}

----------------------------------Test--------------------------------------

public static void main(String[] args) {
//System.out.println(test());
try {
dir(new File("F://ddd"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

System.out.println(reverseString("a/2b/3c/4d/efg"));

System.out.println(reverseString2("a/bb/ccc/dddd"));
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: