Thinking process

how to find the consecutive "++"

  • starting from the second character of the string, if the previous one is "+" as well, then replace these two positions with '-'
public class Solution {
    public List<String> generatePossibleNextMoves(String s) {
        List<String> result = new ArrayList<>();

        for (int i = 1; i < s.length(); ++i) {
            if (s.charAt(i) == '+' && s.charAt(i - 1) == '+') {
                char[] chars = s.toCharArray();
                chars[i] = '-';
                chars[i - 1] = '-';
                result.add(new String(chars));
            }
        }

        return result;
    }
}

Improve => using substring

public class Solution {
    public List<String> generatePossibleNextMoves(String s) {
        List<String> result = new ArrayList<>();

        for (int i = 1; i < s.length(); ++i) {
            if (s.charAt(i) == '+' && s.charAt(i - 1) == '+') {
                result.add(s.substring(0, i - 1) + "--" + s.substring(i + 1));
            }
        }

        return result;
    }
}

results matching ""

    No results matching ""