【解決方法】コーディングに挑戦。 Javaでそれを解決する方法についてのアイデアはありますか?


Question —



|s| is the length of string s. Form a new string b as follows.



String b is initially empty.



For each i where 1 ≤ i ≤ |s|:



Append s[i-1] to the end of b.

Reverse the string b.

Before creating b, reorder s to produce the b that is the lexicographically maximum possible.



Example

s = "011".



Reorder s from "011" to "101". String b is formed as follows.



b after

--------------

Operation Append Reverse

--------- ------ -------

1 1 1

2 10 01

3 011 110



Return "101", the permutation of s that generates the maximum possible b.



Function Description



Create the custom function with parameter that accepts String.

Returns - string: the permutation of s that generates the maximal b



Sample Case 0

Sample Input For Custom Testing



STDIN FUNCTION

----- --------

1100 → s = "1100"



Sample Output

0101



Explanation

Using the permutation "0101":



b after

--------------

Operation Append Reverse

--------- ------ -------

1 0 0

2 01 10

3 100 001

4 0011 1100

Constraints

1 ≤ |s| ≤ 10^5

The string s consists only of characters ‘0’ and ‘1’.

I also have done the research and found the code that is similar to what I am looking for but it is in C++ and I don't understand it..

   string getOptimalString(string s) {
   string ans;
   int n=s.length();
   sort(s.begin(),s.end());
   reverse(s.begin(),s.end());
   if(n%2) ans.push_back(s[n/2]);
      for(int i=(n+1)/2,j=(n-2)/2;j>=0 && i<n;j--,i++){
      ans.push_back(s[i]);
      ans.push_back(s[j]);
   }
   return ans;

私が試したこと:

//The attempt I tried below:

public static String getOptimalString(String s) {
    StringBuilder b = new StringBuilder();
    int n = s.length();

    for(int i = 0;i<n;i++){
        if(s.charAt(i)%2 == 0){
            b.append("0");
        }else{
            b.append("s.charAt(i)");}}
            b = new StringBuilder(s).reverse();return b.toString();
        }

    public static void main(String[] args) throws IOException{
    System.out.println(getOptimalString("1100"));
    }
//From input "1100" the expected result should "0101" but I get "0011"... 

解決策 1

私たちは立ち往生している人々を喜んで助けますが、それは私たちがあなたのためにすべてをするためにここにいるという意味ではありません! 私たちがすべての作業を行うことはできません。あなたはこれに対して報酬を受け取っているか、またはそれはあなたの成績の一部であり、私たちがあなたのためにすべてを行うことはまったく公平ではありません.

だから私たちはあなたが仕事をする必要があり、あなたが行き詰まったときにあなたを助けます. それは、あなたが提出できる段階的な解決策を提供するという意味ではありません!
現在の状況と、プロセスの次のステップを説明することから始めます。 次に、その次のステップを機能させるために何を試みたか、またその際に何が起こったかを教えてください。

開始するのに問題がある場合は、これが役立つ場合があります。 問題を解決するためのコードの書き方、初心者向けガイド[^]

解決策 2

見つけた C コードを Java に変換しました。 しかし、C コードは別の問題に対する解決策です。 質問をもう一度読み、要件を確認してください。

For each i where 1 ≤ i ≤ |s|:

Append s[i-1] to the end of b.

したがって、i を 1 から n-1 まで反復し、文字を指定どおりに移動するループが必要です。
それで、それに取り組み、結果を印刷します。

それが正しく機能したら、次のステップに進みます。

Reverse the string b.

そして最後に、上記の両方が機能しているとき、最初の部分を実装します。

Before creating b, reorder s to produce the b that is the lexicographically maximum possible.

コメント

タイトルとURLをコピーしました