The problem requires us to transform a given string by swapping specific characters and then
reversing the result. Specifically, we need to
replace every 'p' with 'q'
and
vice versa
. After
processing the entire string,
we
reverse it
to get
the final output.
import java.util.Scanner; public class CF { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int testCases = sc.nextInt(); while(testCases>0){ String str = sc.next(); StringBuilder sb = new StringBuilder(); for(int i=0;i<str.length();i++){ char ch = str.charAt(i); if(ch=='p'){ sb.append('q'); } else if(ch=='q') sb.append('p'); else sb.append(ch); } System.out.println(sb.reverse()); testCases--; } } }
The algorithm processes each character of the string once, making it linear in time complexity.
The algorithm uses additional space to store the transformed string, which is proportional to the input size.