848. 字母移位
JalanJiang opened this issue · 2 comments
JalanJiang commented
JalanJiang commented
class Solution:
def shiftingLetters(self, S: str, shifts: List[int]) -> str:
length = len(shifts)
num = [0 for _ in range(length)]
num[length - 1] = shifts[length - 1]
for i in range(length - 2, -1, -1):
num[i] = shifts[i] + num[i + 1]
s_list = list(S)
ord_a = ord('a')
ord_z = ord('z')
for i in range(length):
shift = num[i] % 26
c = s_list[i]
ord_res = ord(c) + shift
if ord_res > ord_z:
ord_res = ord_res - ord_z - 1 + ord_a
s_list[i] = chr(ord_res)
return "".join(s_list)csming1995 commented
Java解法:
class Solution {
public String shiftingLetters(String S, int[] shifts) {
char[] chars = S.toCharArray();
for (int i = 0; i < S.length(); i++) {
for (int j = 0; j < i; j++) {
shifts[j] = (shifts[i] + shifts[j]) % 26;
}
}
for (int i = 0; i < S.length(); i++) {
int index = chars[i] - 'a';
int finalIndex = (index + shifts[i]) % 26;
chars[i] = (char) ('a' + finalIndex);
}
return new String(chars);
}
}