0

我无法让以下程序正常工作。N当它在字符串中遇到 an时dursend,它使用.split. 然后它1为每个 single收集 a N2为一个 N 收集 a ,然后是一个Q,依此类推。然后0必须收集的数量等于Q's 的数量。正确的输出应该是: 011111120111111201111111111111111其中第一个0应该被忽略。我得到的输出是:01111112011111201111111111111110,所以似乎0在第一次打印之后2程序出错了:它给出了 5 次1而不是 6 次1

public class T3 {
  public static void main(String[] args)
  {
    String durs = "NNNNNNNQNNNNNNNQNNNNNNNNNNNNNNNN";
    System.out.println(durs);
    int d = countOccurrencesDurations(durs, 'N');
    int d1 = countOccurrencesDurations(durs, 'Q');
    int m = 32;
    int[] cdn = new int[m];
    int d2;
    StringBuffer sb = new StringBuffer(durs);
    String dursend = sb.append("W").toString();
    String[] a = new String[d];
    a = dursend.split("N");
    // int alen = a.length + d1 - 1;
    // System.out.println("a: " + alen);
    int i = 1;
    while (i < a.length) {
      // System.out.println("N" + a[i]);
      d2 = countOccurrencesDurations(a[i], 'Q');
      // System.out.println(d2);
      int d3 = d2 + 1;
      cdn[i] += d3;
      for (int j = 0; j < d2; j++) {
        i++;
        cdn[i] += 0;
      }
      i++;
    }
    for (int k = 0; k < m; k++) {
      System.out.print(cdn[k]);
    }
  }

  public static int countOccurrencesDurations(String haystack, char needle)
  {
    int count = 0;
    for (int i = 0; i < haystack.length(); i++) {
      if (haystack.charAt(i) == needle) {
        count++;
      }
    }
    return count;
  }
}
4

2 回答 2

0

如果您需要一个有效的解决方案,您可以使用它。我根据您的评论更新了我的解决方案。

public class Main {

    private static String result;

    public static void main(String[] args) {
        String durs = "NNNNNNQQNNNNNNNQNNNNNNNNNNNNNNNN";

        result = "";

        int qCount = 0;
        for(int i = 0; i < durs.length(); i++){
            if (durs.charAt(i) == 'N'){
                // Process accumulated Q's from before
                if (qCount > 0){
                    processQ(qCount);
                    qCount = 0;
                }

                // Do nothing if there is a Q next to us
                if ((i != durs.length() - 1) && durs.charAt(i + 1) == 'Q'){
                    continue;
                }

                result += "1";


            }else{
                qCount++;
            }
        }

        if (qCount > 0){
            processQ(qCount);
        }


        System.out.println(result);
    }

    private static void processQ(int qCount) {
        if (qCount > 0){
            result += (qCount + 1);
            for(int j = 0; j < qCount; j++){
                result += "0";
            }
        }
    }

}

我相信这个工作正常。

于 2013-03-14T22:15:34.290 回答
0

您可以尝试这个简化版本(与您的实现有些一致):

StringBuilder sb = new StringBuilder();
char last = 0;
for (char c : durs.toCharArray()) {
    if (c == 'Q' && last == 'N') {
        sb.deleteCharAt(sb.length() - 1);
        sb.append("20");
    } else if (c == 'N') {
        sb.append("1");
    }
    last = c;
}
System.out.println(sb.toString());
于 2013-03-14T22:18:03.140 回答