我参加了一次编码面试,并给出了这个问题。给定一个单词字符串,将该字符串分解为单词并将它们分行输出,每行长度不超过 N 个字符。给我的 sample 是“一件红色毛衣”。行长为 8。单词不能分解,每行必须容纳尽可能多的单词。因此,对于给定的示例,“A”和“红色”将适合一条线和“毛衣”。添加到该行的字符长度超过了允许的字符长度,因此它将在新行上输出。
我首先将字符串拆分为字符串 []。然后创建一个接受 String [] 和行长度的方法。我对边缘情况做了一些假设,然后循环遍历 String []。这是我对可以用什么来表示单行以及如何在单行上添加子数组感到非常困惑的地方。我查找了可以找到所有接近总和的子数组的算法,但它似乎会回收元素,而我无法做到这一点。
这是我在时间耗尽之前得到的信息:
import java.util.ArrayList;
import java.util.List;
class Solution {
public static void main(String[] args) {
String sentence = "A red sweater.";
String[] words = sentence.split(" ");
Solution newSol = new Solution();
System.out.println(newSol.convertToLines(words, 8));
}
public List<String> convertToLines(String[] myArr, int bound) {
List<String> result = new ArrayList<String>();
if (myArr.length == 0) {
return result;
}
for (int i = 0; i < myArr.length; i++) {
if (myArr[i].length() > bound) {
System.out.println("One or more words is larger than your boundary");
break;
}
//This is where I got into trouble
//This doesn't account for more than 2 elements
//nor how I would output them on separate lines
if (myArr[i].length() + myArr[i].length() <= bound) {
result.add(myArr[i] + " " + myArr[i + 1]);
} else {
result.add(myArr[i]);
}
}
return result;
}
}
我到处寻找这个特定的问题,但找不到它。我认为有一个模式或我缺少的东西,但经过几个小时的困惑,我仍然不知道从这里该去哪里。我从未编写过类似的代码。虽然面试已经晚了,但我还是想知道如何解决这个问题,以便我能够从中吸取教训,继续学习。
最佳答案
Gabriel Rouleau 上面的代码在循环中迭代时会跳过很多单词。
例如在字符串“A red mother”中。它将循环“A”,添加到 line
变量,然后将“red”添加到 line
变量,然后迭代毛衣但不添加到 line 变量。它永远不会被重新访问以添加到下一行中。
通过使用原始 for 循环语法进行迭代并在下一行需要重新访问单词时递减迭代索引来解决该问题。
String sentence = "A red sweater with some other stuff.";
String[] words = sentence.split(" ");
int bound = 8;
if(words.length == 0) return;
String line = "";
Boolean first = true;
for (int i = 0; i < words.length; i++) {
if(first) {
line = words[i];
first = false;
} else {
if ((line + " " + words[i]).length() < bound) {
line += " " + words[i];
} else {
System.out.println(line);
line = words[i];
first = true;
i--;
}
}
}
System.out.println(line);
此外,此代码还修复了原始问题所存在的问题(考虑超过 2 个元素)。
代码已测试并成功运行!
关于java - 如何在单独的行上输出字符串数组,每行允许有 N 个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68687226/