848. Shifting Letters
Вам дана 字符串 s из строчных букв английского алфавита и 整数 数组 shifts такой же длины.
Назовем shift() буквы следующей буквой в алфавите (с переходом так, что 'z' становится 'a').
На示例, shift('a') = 'b', shift('t') = 'u', и shift('z') = 'a'.
Теперь для каждого shifts[i] = x мы хотим сдвинуть первые i + 1 букв строки s на x раз.
return итоговую строку после Applications всех таких сдвигов к s.
示例:
Input: s = "abc", shifts = [3,5,9]
Output: "rpl"
Explanation: We start with "abc".
After shifting the first 1 letters of s by 3, we have "dbc".
After shifting the first 2 letters of s by 5, we have "igc".
After shifting the first 3 letters of s by 9, we have "rpl", the answer.
C# 解法
匹配/原始public class Solution {
public string ShiftingLetters(string s, int[] shifts) {
var result = new char[s.Length];
int totalShifts = 0;
foreach (int shift in shifts) {
totalShifts = (totalShifts + shift) % 26;
}
for (int i = 0; i < s.Length; ++i) {
int newCharValue = (s[i] - 'a' + totalShifts) % 26;
result[i] = (char)(newCharValue + 'a');
totalShifts = (totalShifts - shifts[i] + 26) % 26;
}
return new string(result);
}
}
C++ 解法
自动草稿,提交前请检查#include <bits/stdc++.h>
using namespace std;
// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
public string ShiftingLetters(string s, vector<int>& shifts) {
var result = new char[s.size()];
int totalShifts = 0;
foreach (int shift in shifts) {
totalShifts = (totalShifts + shift) % 26;
}
for (int i = 0; i < s.size(); ++i) {
int newCharValue = (s[i] - 'a' + totalShifts) % 26;
result[i] = (char)(newCharValue + 'a');
totalShifts = (totalShifts - shifts[i] + 26) % 26;
}
return new string(result);
}
}
Java 解法
匹配/原始class Solution {
public String shiftingLetters(String S, int[] shifts) {
StringBuilder ans = new StringBuilder();
int X = 0;
for (int shift: shifts)
X = (X + shift) % 26;
for (int i = 0; i < S.length(); ++i) {
int index = S.charAt(i) - 'a';
ans.append((char) ((index + X) % 26 + 97));
X = Math.floorMod(X - shifts[i], 26);
}
return ans.toString();
}
}
JavaScript 解法
匹配/原始var shiftingLetters = function(s, shifts) {
let totalShifts = shifts.reduce((sum, shift) => (sum + shift) % 26, 0);
const sArray = s.split('');
for (let i = 0; i < sArray.length; i++) {
let newCharValue = (sArray[i].charCodeAt(0) - 'a'.charCodeAt(0) + totalShifts) % 26;
sArray[i] = String.fromCharCode(newCharValue + 'a'.charCodeAt(0));
totalShifts = (totalShifts - shifts[i] + 26) % 26;
}
return sArray.join('');
};
Python 解法
匹配/原始class Solution:
def shiftingLetters(self, s: str, shifts: List[int]) -> str:
s = list(s)
totalShifts = sum(shifts) % 26
for i in range(len(s)):
newCharValue = (ord(s[i]) - ord('a') + totalShifts) % 26
s[i] = chr(newCharValue + ord('a'))
totalShifts = (totalShifts - shifts[i]) % 26
return ''.join(s)
Go 解法
匹配/原始func shiftingLetters(s string, shifts []int) string {
totalShifts := 0
for _, shift := range shifts {
totalShifts = (totalShifts + shift) % 26
}
result := make([]byte, len(s))
for i := 0; i < len(s); i++ {
newCharValue := (int(s[i]-'a') + totalShifts) % 26
result[i] = byte(newCharValue + 'a')
totalShifts = (totalShifts - shifts[i] + 26) % 26
}
return string(result)
}
Algorithm
Вычислите общее количество сдвигов для всех символов строки, используя 数组 shifts.
Пройдите по строке s и примените вычисленные сдвиги к каждому символу, начиная с первого и уменьшая количество сдвигов на текущем шаге.
Постройте и return итоговую строку после всех сдвигов.
😎
Vacancies for this task
活跃职位 with overlapping task tags are 已显示.