1. 二进制求和
给定两个二进制字符串 a 和 b ,以二进制字符串的形式返回它们的和。
class Solution:
def addBinary(self, a: str, b: str) -> str:
i = len(a) - 1
j = len(b) - 1
carry = 0
result = []
while i >= 0 or j >= 0 or carry:
digit_a = int(a[i]) if i >= 0 else 0
digit_b = int(b[j]) if j >= 0 else 0
sum_digits = digit_a + digit_b + carry
carry = sum_digits // 2
result.append(str(sum_digits % 2))
i -= 1
j -= 1
return ''.join(result[::-1])
2. 文本左右对齐
给定一个单词数组 words 和一个长度 maxWidth ,重新排版单词,使其成为每行恰好有 maxWidth 个字符,且左右两端对齐的文本。
class Solution {
public List<String> fullJustify(String[] words, int maxWidth) {
List<String> stringList = new ArrayList<>();
List<Integer> index = new ArrayList<>();
int width = 0;
int length = 0;
StringBuilder stringBuilder;
for (int i = 0; i < words.length; ) {
width += words[i].length();
length = width - words[i].length();
if (width < maxWidth - index.size() + 1) {
index.add(i);
i++;
} else {
int nullLen = (maxWidth - length);
stringBuilder = new StringBuilder();
int after = (index.size() - 1) == 0? 1 : index.size() - 1;
int[] arrs = new int[after];
for (int j = 0; nullLen > 0; ) {
arrs[j]++;
nullLen--;
j = (j + 1) % arrs.length;
}
for (int j = 0; j < index.size(); j++) {
if (j!= index.size() - 1 || j == 0) {
stringBuilder.append(words[index.get(j)]);
for (int k = 0; k < arrs[j]; k++) {
stringBuilder.append(" ");
}
} else {
stringBuilder.append(words[index.get(j)]);
}
}
stringList.add(stringBuilder.toString());
width = 0;
index = new ArrayList<>();
}
}
length = 0;
for (Integer i : index) {
length += words[i].length();
}
stringBuilder = new StringBuilder();
for (int i = 0; i < index.size(); i++) {
if (i == index.size() - 1) {
stringBuilder.append(words[index.get(i)]);
} else {
stringBuilder.append(words[index.get(i)]).append(" ");
length++;
}
}
for (int i = 0; i < maxWidth - length; i++) {
stringBuilder.append(" ");
}
stringList.add(stringBuilder.toString());
return stringList;
}
}
标签:index,int,stringBuilder,Study,Part34,length,Algorithms,words,append
From: https://www.cnblogs.com/stephenxiong001/p/18421550