乐信2018在线笔试编程题之一

原题大意是,输入一个字符串,和一个特定的字符,其中字符是字符串其中的一个,然后求字符串中的每一个字符距离这个特定字符的最短距离。

比如:

输入 :lexiabiab

             i

输出:3,2,1,0,1,1,0,1,2

解题:

import java.util.Scanner;

public class Main
{	
	public static void main(String[] args)
	{
		//输入
		Scanner in = new Scanner(System.in);
		String str = in.nextLine();
		String ch = in.nextLine();
		
		System.err.println(Main.getResult(str,ch));
		
		in.close();
	}

	public static String getResult(String str , String ch)
	{
		StringBuffer result = new StringBuffer();
		char[] arrs = str.toCharArray();//转换为字符串
		char c = ch.toCharArray()[0];
		int preIndex=0;//保存前一个ch字符所在的索引位置
		for(int i=0;ipreIndex)
				{
					result.append(Math.abs(index-i)>Math.abs(preIndex-i)?Math.abs(preIndex-i)+",":Math.abs(index-i)+",");
					if(i == index)
						preIndex=index;
				}
				else
				{
					result.append(Math.abs(index-i)+",");
					preIndex=index;
				}
			}
			if(i>index) result.append(Math.abs(index-i)+",");
			
		}
		result.deleteCharAt(result.length()-1);
		return result.toString();
	}

    //获取从pos开始查找,arrs中和c相等的位置索引,并返回
	public static int getIndex(char[] arrs , char c,int pos)
	{
		
		for(int i=pos;i

 

你可能感兴趣的:(小算法,Java)