【问题标题】:How to Find Longest Distance b/w char in String如何在字符串中找到最长距离的黑白字符
【发布时间】:2017-05-21 09:08:20
【问题描述】:
public class LongestAlphabetDistance {

    public int longDistance(String str, String a) {
        str = "this is my greatest achievement in the world";
        a = "i";
        int count =0;
        // code logic for longest difference
        return count;
    }
}

我想首先获得“这是我在世界上最伟大的成就”的距离 a = i 最后我喜欢t=1,h=2,i=3,s=4, 空格不应该比i=5,s=6,m=7,y=8,g=9 喜欢最后i "in" i=27 所以首先i=3 最后i=27 所以最长距离b/w 24 请写代码为此

【问题讨论】:

  • 你能分享一下你到目前为止的尝试吗?
  • 我们不是来帮你做作业的
  • SO 是为了提出问题而不是为了做你的工作!
  • @ControlAltDel 老实说,我什至不明白这个问题。程序应该只计算String(减去空格)中的字符数量还是字符之间的距离?还有一个错字,应该是achievement。
  • 作业与否,这对我来说似乎是一个代码编写请求,这在 Stack Overflow 上并不受欢迎。

标签: java arrays sorting logic


【解决方案1】:
public class LongestAlphabetDistance {

    public int longDistance(String str, String a) {
        str = "this is my greatest achivement in the world";
        a = "i";
        str = str.replaceAll("\\s", "");
        char[] chArray = str.toCharArray();
        ArrayList<Integer> inArray = new ArrayList<>();

        for(int i =0;i<chArray.length;i++) {
            if(chArray[i] == a.charAt(0) ) {
                inArray.add(i+1);
            }
        }

        return inArray.get(inArray.size()-1)-inArray.get(0); // 24 
    }
}

【讨论】:

    【解决方案2】:

    您可以使用indexOf 获取字符的第一个索引,并使用lastIndexOf 获取最后一个索引,例如:

    String str = "this is my greatest achivement in the world";
    String a = "i";
    
    int indexFirst = str.replace(" ", "").indexOf(a);//this return 2
    int indexLast = str.replace(" ", "").lastIndexOf(a);//this return 26
    
    int dist = indexLast - indexFirst; //this return 24
    

    注意这两个方法indexOflastIndexOf都是从0开始的,因为你得到的是2和24而不是3和27

    【讨论】:

      【解决方案3】:

      拼写正确,距离为25:

      public static void main(String[] args) {
      
              String str = "this is my greatest achievement in the world".replaceAll(" ", "");
              String a = "i";
              int firstI = str.indexOf(a);
              int lastI = str.lastIndexOf(a);
      
              System.out.printf("%s%n%s%d%n%s%d%n%s%d", str, "First i: ", firstI, "Last i: ", lastI, "Distance: ", (lastI - firstI));
      
          }
      

      输出:

      thisismygreatestachievementintheworld
      First i: 2
      Last i: 27
      Distance: 25
      

      【讨论】:

        猜你喜欢
        • 2011-05-11
        • 1970-01-01
        • 2012-09-14
        • 1970-01-01
        • 2019-12-10
        • 2017-05-30
        • 2014-08-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多