Java String Reverse

  • + 0 comments

    The previous one-liner solution is awsome! My idea was to use "converging iterators" approach that works in-place without copying the data (sub-strings, concatenation, etc.). What's more, this approach is very fast as it may give an answer even before reading the whole string, possibly after comparing just two letters!

    import java.util.Scanner;
    
    public class Solution {
        private static boolean isPalindrome(String str) {
            for (int f = 0, r = str.length()-1; f < r; ++f, --r) {
                if (str.charAt(f) != str.charAt(r))
                    return false;
            }
            return true;
        }
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            String str = sc.nextLine();
            sc.close();
            System.out.println(isPalindrome(str) ? "Yes" : "No");
        }
    }