0

Java で文字列内の文字のインデックス配列を返すメソッドを作成する必要があります。以下は適切ですか (正確性、効率性、可能な限り短いコード)?

int[] charIndexArray(String s, char c) {
    int start = 0;
    List<Integer> list = new ArrayList<Integer>();
    while ((start = s.indexOf(c, start)) != -1) {
        list.add(start);
        start++;
    }
    int arr[] = new int[list.size()];
    for (int i = 0; i < ret.length; i++)
        arr[i] = list.get(i);
    return arr;
}
4

3 に答える 3

1

それを配列にコピーする最後のコードをtoArray() メソッドの呼び出しに置き換えることができます。それ以外は、かなりよく見えます。

于 2012-04-27T22:25:40.157 に答える
1

それ以外の:

while ((start = s.indexOf(c, start)) != -1) {
    list.add(start);
    start++;
}

検討:

for (int i = 0; i < s.length(); i++) {
    if (s.charAt(i) == c) {
      list.add(i);
    }
 }

indexOf により、別のループ全体が作成され、キャラクターの次のインスタンスが検索されるためです。

あなたのコードは静かにやっています:

while (start != -1) {
    start = -1;
    for ( int i=start;i<s.length();i++){
      if ( charAt(i) == c ) {
        start = i;
        break;
      }
    }
    if ( start != -1 ) { 
    list.add(start);
    start++;
  }
}

これはより効率的ではないようです。しかし、これにあまりにも多くの時間を費やした後、次のことが判明しました。

static int[] charIndexArrayByBits(String s, char c) {
    int start = 0;
    int[] list = new int[s.length()];
    int count = -1;
    while ((start = s.indexOf(c, start)) != -1) {
      list[++count] = start;
      start++;
    }
    return Arrays.copyOf(list, count);
  }

より高速です。しかし、空間的により大きな int 配列を割り当てているため、一般的なケースではより効率的だとは思いません。

于 2012-04-27T22:42:18.397 に答える
0

コードがうまく見えません。

1 つではなく 2 つのループを使用します。

メソッドを使用してみてください。

文字列および Arrays.copy の場合は charAt(int pos)

OPはもっと読むべきではありません;p

1 つ目は、この種のメソッドをいくつかのユーティリティ クラスに配置し、静的な IMHO にする必要がある場所です。

public class CharSequenceUtil {

    private static int[] EMPTY_INT_ARRAY = new int[0];

    /**
    * Method search the position of given character in char sequence.
    *
    * @param CharSequence seq - Sequence of char that will be investigate 
    * @param char c - Character that is analysed.
    *
    * @return int array with positions of char c in CharSequence instanace
    * @throws NullPointerException if seq is null.
    */
    public static int[] charIndexArray(CharSequence seq, char c) {

      if(seq == null) {
        throw new NullPointerExcetion("The seq must not be null");
      }

      if(seq.length() == 0) {
        return EMPTY_INT_ARRAY;
      }

      int[] positions = new int[seq.lenth()];
      int stor = -1; 

      for(int pos = 0; pos < seq.length(); seq++) {
         if(c == seq.charAt(pos)) {
          positions[++stor] = pos;
         }
      }

      if(stor == -1) {
        return EMPTY_INT_ARRAY;
      }

      return Arrays.copyOf(positions, stor);
    }
}
于 2012-04-27T22:28:40.127 に答える