Skip to content

2810. Faulty Keyboard 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  string finalString(string s) {
    deque<char> dq;
    bool inversed = false;

    for (const char c : s)
      if (c == 'i')
        inversed = !inversed;
      else if (inversed)
        dq.push_front(c);
      else
        dq.push_back(c);

    return inversed ? string{dq.rbegin(), dq.rend()}
                    : string{dq.begin(), dq.end()};
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  public String finalString(String s) {
    StringBuilder sb = new StringBuilder();
    Deque<Character> dq = new ArrayDeque<>();
    boolean inversed = false;

    for (final char c : s.toCharArray())
      if (c == 'i')
        inversed = !inversed;
      else if (inversed)
        dq.addFirst(c);
      else
        dq.addLast(c);

    while (!dq.isEmpty())
      sb.append(dq.pollFirst());

    return inversed ? sb.reverse().toString() : sb.toString();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def finalString(self, s: str) -> str:
    dq = collections.deque()
    inversed = False

    for c in s:
      if c == 'i':
        inversed = not inversed
      elif inversed:
        dq.appendleft(c)
      else:
        dq.append(c)

    return ''.join(reversed(dq)) if inversed else ''.join(dq)