import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * @author: ycz * @date: 2018/12/17 0017 16:43 * @description: */ public class Distance { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine(); String str1 = str; String ch = sc.nextLine(); List<Integer> list = getCharList(str1,ch); List<Integer> result = new ArrayList<>(); for (int p=0;p<str.length();p++){ if (p <= list.get(0)){ result.add(list.get(0)-p); }else if (p >= list.get(list.size()-1)){ result.add(p-list.get(list.size()-1)); }else { for (int q=1;q<list.size();q++){ if (list.get(q) >= p){ result.add(compare(list.get(q-1),list.get(q),p)); break; } } } } System.out.println(result.toString()); } //得到ch位置数组 private static List<Integer> getCharList(String str1,String ch){ List<Integer> list = new ArrayList<>(); int i=0; int j=0; while (str1.contains(ch)){ i = str1.indexOf(ch); list.add(i+j); j = i + j +1; str1 = str1.substring(i+1); } return list; } //比较不是头尾段的其他字符与char的距离 private static int compare(int ch1,int ch2,int num){ int d1 = num - ch1; int d2 = ch2 - num; if (d1 < d2){ return d1; } return d2; } }
【Java】给定一个字符串str,和一个字母ch,请实现相应的代码求出一个数组,使数组中每个数字表示该位置与字母ch之间的最短距离。 比如str=”lexinfintech” ch=”i” 则输出为:[3,2,1,0,1,1,0,1,2,3,4,5]
猜你喜欢
转载自www.cnblogs.com/hyczzz/p/10132893.html
今日推荐
周排行