553. [字符串]最优除法
553. 最优除法
本题所考察的是:如何进行字符串拼接。
为了获得最大的除法结果,应该让 被除数 尽可能较大,而 除数 尽可能小,那么仅需要考虑:① 如果 \(nums.length ≤ 2\) 时,输出时应不带括号;② 如果 \(nums.length > 2\) 时,应该在第二位数字前加上左括号,在最后一位数字后加上右括号。
// 执行用时: 13 ms , 在所有 Java 提交中击败了 21.40% 的用户
// 内存消耗: 37.2 MB , 在所有 Java 提交中击败了 33.11% 的用户
class Solution {
public String optimalDivision(int[] nums) {
// 被除数尽可能大,除数尽可能小
// 基于这一种想法,只需要将括号加在第二个数前和最后一个数后
if (nums.length == 1){
return Integer.toString(nums[0]);
}
if (nums.length == 2){
return nums[0] + "/" + nums[1];
}
String res = nums[0]+ "/(" + nums[1];
for(int i = 2; i < nums.length - 1; i++){
res = res + "/" + nums[i];
}
return res + "/" + nums[nums.length - 1] + ")";
}
}
当然,使用 StringBuffer() 或 StringBuilder() 会更加高效。
// 执行用时: 0 ms , 在所有 Java 提交中击败了 100.00% 的用户
// 内存消耗: 36.2 MB , 在所有 Java 提交中击败了 98.68% 的用户
class Solution {
public String optimalDivision(int[] nums) {
StringBuilder res = new StringBuilder();
res.append(nums[0]);
if (nums.length == 1) return res.toString();
if (nums.length == 2){
res.append('/').append(nums[1]);
return res.toString();
}
res.append("/(");
for (int i = 1; i < nums.length - 1; i ++){
res.append(nums[i]).append('/');
}
res.append(nums[nums.length - 1]).append(')');
return res.toString();
}
}

浙公网安备 33010602011771号