293. Flip Game

LeetCode easy original: C# #array #csharp #easy #leetcode #queue #string #tree
Văn bản bài toán được dịch từ tiếng Nga theo ngôn ngữ giao diện. Mã không thay đổi.

Вы играете в игру Flip со своим другом.

Вам дана chuỗi currentState, которая содержит только символы '+' и '-'. Вы и ваш друг по очереди переворачиваете две последовательные "++" в "--". Игра заканчивается, когда один из игроков больше не может сделать ход, и, следовательно, другой игрок становится победителем.

return все возможные состояния строки currentState после одного допустимого хода. Вы можете вернуть ответы в любом порядке. Если допустимых ходов нет, return пустой список [].

Ví dụ:

Input: currentState = "++++"

Output: ["--++","+--+","++--"]

C# lời giải

đã khớp/gốc
using System;
using System.Collections.Generic;
public class Solution {
    public IList<string> GeneratePossibleNextMoves(string currentState) {
        var nextPossibleStates = new List<string>();
        for (int index = 0; index < currentState.Length - 1; index++) {
            if (currentState[index] == '+' && currentState[index + 1] == '+') {
                string nextState = currentState.Substring(0, index) + "--" + currentState.Substring(index + 2);
                nextPossibleStates.Add(nextState);
            }
        }
        return nextPossibleStates;
    }
}

C++ lời giải

bản nháp tự động, xem lại trước khi gửi
#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 vector<string> GeneratePossibleNextMoves(string currentState) {
        var nextPossibleStates = new List<string>();
        for (int index = 0; index < currentState.size() - 1; index++) {
            if (currentState[index] == '+' && currentState[index + 1] == '+') {
                string nextState = currentState.Substring(0, index) + "--" + currentState.Substring(index + 2);
                nextPossibleStates.push_back(nextState);
            }
        }
        return nextPossibleStates;
    }
}

Java lời giải

đã khớp/gốc
import java.util.ArrayList;
import java.util.List;

public class Solution {
    public List<String> generatePossibleNextMoves(String currentState) {
        List<String> nextPossibleStates = new ArrayList<>();

        for (int index = 0; index < currentState.length() - 1; index++) {
            if (currentState.charAt(index) == '+' && currentState.charAt(index + 1) == '+') {
                String nextState = currentState.substring(0, index) + "--" + currentState.substring(index + 2);
                nextPossibleStates.add(nextState);
            }
        }

        return nextPossibleStates;
    }
}

JavaScript lời giải

đã khớp/gốc
class Solution {
    generatePossibleNextMoves(currentState) {
        const nextPossibleStates = [];

        for (let i = 0; i < currentState.length - 1; i++) {
            if (currentState[i] === '+' && currentState[i + 1] === '+') {
                const nextState = currentState.slice(0, i) + "--" + currentState.slice(i + 2);
                nextPossibleStates.push(nextState);
            }
        }

        return nextPossibleStates;
    }
}

Python lời giải

đã khớp/gốc
class Solution:
    def generatePossibleNextMoves(self, currentState: str) -> list[str]:
        nextPossibleStates = []

        for index in range(len(currentState) - 1):
            if currentState[index] == "+" and currentState[index + 1] == "+":
                nextState = currentState[:index] + "--" + currentState[index + 2:]
                nextPossibleStates.append(nextState)

        return nextPossibleStates

Go lời giải

đã khớp/gốc
package main

func generatePossibleNextMoves(currentState string) []string {
    var nextPossibleStates []string

    for i := 0; i < len(currentState)-1; i++ {
        if currentState[i] == '+' && currentState[i+1] == '+' {
            nextState := currentState[:i] + "--" + currentState[i+2:]
            nextPossibleStates = append(nextPossibleStates, nextState)
        }
    }

    return nextPossibleStates
}

Algorithm

Создайте пустой mảng nextPossibleStates для хранения всех возможных следующих состояний после одного хода.

Запустите цикл от index = 0 до currentState.size() - 1. Для каждого индекса:

Если символы на позициях index и index + 1 равны '+':

Создайте новую строку nextState, заменив две последовательные '+' на '--'.

Используйте конкатенацию строк для создания nextState из подстроки до первого '+', "--" и подстроки после второго '+' до конца.

Сохраните созданное nextState в mảng nextPossibleStates.

После цикла return mảng nextPossibleStates, содержащий все возможные следующие состояния.

😎

Vacancies for this task

việc làm đang hoạt động with overlapping task tags are đã hiển thị.

Tất cả việc làm
Chưa có việc làm đang hoạt động.