头脑风暴
Swap Adjacent in LR String
class Solution {
public boolean canTransform(String start, String end) {
if (start.equals(end)) return true;
Queue<String> queue = new LinkedList<>();
Set<String> visited = new HashSet<>();
queue.offer(start);
visited.add(start);
while (!queue.isEmpty()) {
String cur = queue.poll();
for (int i = 0; i < cur.length() - 1; i++) {
if (cur.substring(i, i + 2).equals("XL")) {
String next = cur.substring(0, i) + "LX" + cur.substring(i + 2);
if (next.equals(end)) return true;
if (visited.contains(next)) continue;
queue.offer(next);
visited.add(next);
}
if (cur.substring(i, i + 2).equals("RX")) {
String next = cur.substring(0, i) + "XR" + cur.substring(i + 2);
if (next.equals(end)) return true;
if (visited.contains(next)) continue;
queue.offer(next);
visited.add(next);
}
}
}
return false;
}
}Last updated