848. Shifting Letters

LeetCode medium original: C# #array #csharp #leetcode #medium #string
Task text is translated from Russian for the selected interface language. Code is left unchanged.

Вам дана string s из строчных букв английского алфавита и integer array shifts такой же длины.

Назовем shift() буквы следующей буквой в алфавите (с переходом так, что 'z' становится 'a').

НаExample, shift('a') = 'b', shift('t') = 'u', и shift('z') = 'a'.

Теперь для каждого shifts[i] = x мы хотим сдвинуть первые i + 1 букв строки s на x раз.

return итоговую строку после Applications всех таких сдвигов к s.

Example:

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# solution

matched/original
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++ solution

auto-draft, review before submit
#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 solution

matched/original
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 solution

matched/original
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 solution

matched/original
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 solution

matched/original
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

Вычислите общее количество сдвигов для всех символов строки, используя array shifts.

Пройдите по строке s и примените вычисленные сдвиги к каждому символу, начиная с первого и уменьшая количество сдвигов на текущем шаге.

Постройте и return итоговую строку после всех сдвигов.

😎

Vacancies for this task

Active vacancies with overlapping task tags are shown.

All vacancies
There are no active vacancies yet.