查找字符串中两个字符的距离并将它们输入数组的方法

method to find the the distance of two characters of a string apart and entering them into an array

正在为学校解决这个问题

"给定一个字符串 s 和一个字符 c,return 一个新的整数列表,其长度与 s 相同,其中对于每个索引 i,其值设置为 s[i] 到 c 的最近距离. 你可以假设 c 存在于 s."

例如

输入 s = "aabaab" c = "b"

输出 [2, 1, 0, 1, 1, 0]

我的输出 [63,63,64,63,63]

我不知道我做错了什么,我该怎么办?

public static void main(String []Args) {
    
        String s = "aabaab";
        String c = "b";
        List<Integer> list = new ArrayList<Integer>();
        char[] ch = s.toCharArray();
        int indexofc = new String(ch).indexOf(c);
        
        for(int i=0;i<ch.length;i++) {
            
            int indexofothers = ch[i];
            int result = indexofothers - indexofc;
            if (result<=0) {
                result = result*(-1);
                }
            
            list.add(result);
            
            }
            System.out.println(list);
        }
        
        
        
    }

您的代码有两个主要问题: 首先这一行没有意义

int indexofothers = ch[i];

您正在尝试获取索引,但取的是 i 位置的字符,然后将其转换为整数,结果可能类似于 63。因此请改用 i ch[i].

第二个 indexOf 方法将只 return 第一个索引,如果你像那样使用它的话。添加当前索引(并将其移动到循环中),否则您将始终获得到第一个 b 的距离。所以您的代码可能如下所示:

public static void main(String []Args) {

    String s = "aabaab";
    String c = "b";
    List<Integer> list = new ArrayList<>();
    char[] ch = s.toCharArray();

    for(int i=0;i<ch.length;i++) {
        int indexofc = s.indexOf(c, i);
        int result = i - indexofc;
        if (result<=0) {
            result = result*(-1);
        }
        list.add(result);
    }
    System.out.println(list);
}