我有一個字串,需要在 n 列的二維陣列中垂直排列。String 可能有多個單詞,如果有,目標是將句子每列分成相等的單詞,并將它們垂直排列在 n 列中。一種選擇是按長度排序,將最長的單詞排列在第一列中,然后排列剩余的單詞。
因此,如果我有 8 個單詞,我會在 4 列中各安排 2 個單詞 - 類似這樣的內容或 2 列中的 4 個單詞,以確保我在 n 列中有 n 個單詞。
例如,如果我有“Apple is my 最喜愛的水果,因為它很好吃”,我需要每列安排 3 個詞。我無法弄清楚如何對此進行編碼。我對下面的解決方案的行和列進行了硬編碼,并且我正在嘗試逐步實作它。任何輸入都會非常有幫助。
public static void main(String[] args) {
putin2dArr("Apple is");
}
public static void putin2dArr(String inputString) {
String[] input = inputString.split(" ");
int rows = 0;
int cols = 2;
for (String inptString : input) {
if (inptString.length() > rows) {
rows = inptString.length();
}
}
int col = 0;
char[][] output = new char[rows][cols];
for (String inptString : input) {
for (int i = 0; i < rows; i ) {
if (inptString.length() < rows) {
rows = inptString.length();
while (i < rows) {
output[i][col] = inptString.charAt(i);
i ;
}
} else {
output[i][col] = inptString.charAt(i);
}
}
col ;
if (col == cols) {
break;
}
}
print2dArray(output);
}
public static void print2dArray(char[][] inputStr) {
int rows = inputStr.length;
int cols = inputStr[0].length;
for (int i = 0; i < rows; i ) {
for (int j = 0; j < cols; j ) {
System.out.println(inputStr[i][j]);
}
}
}
uj5u.com熱心網友回復:
假設列數是外部輸入引數,則可以使用輸入字串中的詞來創建和填充二維陣列。
單詞應按長度降序排列。
static String[][] buildTable(String str, int n) {
// prepare sorted array of words
String[] words = Arrays.stream(str.split("\\s "))
.sorted(Comparator.<String>comparingInt(String::length).reversed())
.toArray(String[]::new);
// build the resulting 2D array
String[][] res = new String[words.length / n][n];
for (int i = 0; i < words.length; i ) {
res[i / n][i % n] = words[i];
}
return res;
}
測驗:
String str = "Apple is my favorite fruit because it is yummy";
Arrays.stream(buildTable(str, 3))
.map(Arrays::toString)
.forEach(System.out::println);
輸出
[favorite, because, Apple]
[fruit, yummy, is]
[my, it, is]
uj5u.com熱心網友回復:
嘗試這樣的事情:
public void test() {
String inputStr = "Apple is my favorite fruit because it is";
String[] words = inputStr.split(" ");
int columns = (int) Math.sqrt(words.length);
int c = 0;
for (String word : words) {
System.out.print(word " ");
c = c 1;
if (c == columns) {
System.out.println("");
c = 0;
}
}
}
這個想法是你得到大小平方根的列數。您將專案添加到該列,直到該行已滿,然后您移動到下一個。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/351891.html
標籤:爪哇
