21BCS1704 Tushar 9
21BCS1704 Tushar 9
Java
import java.util.Scanner;
public class PalindromeChecker {
public static boolean isPalindrome(String str) {
int left = 0;
int right = str.length() - 1;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
if (isPalindrome(input)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
scanner.close();
}
}
2. Count primes – Hackerrank
class Solution {
public int countPrimes(int n) {
if (n <= 2)
return 0;
final boolean[] isPrime = sieveEratosthenes(n);
int ans = 0;
return (int) IntStream.range(0, isPrime.length)
.mapToObj(i -> isPrime[i])
.filter(p -> p)
.count();
}
private boolean[] sieveEratosthenes(int n) {
boolean[] isPrime = new boolean[n];
Arrays.fill(isPrime, true);
isPrime[0] = false;
isPrime[1] = false;
for (int i = 2; i * i < n; ++i)
if (isPrime[i])
for (int j = i * i; j < n; j += i)
isPrime[j] = false;
return isPrime;
}
}
return -1;
}
}
4. move zeroes -leetcode
class Solution {
public void moveZeroes(int[] nums) {
int i = 0;
for (final int num : nums)
if (num != 0)
nums[i++] = num;
return ans;
}
}
7. Reverse Words in a String – leetcode
class Solution {
public String reverseWords(String s) {
StringBuilder sb = new StringBuilder(s).reverse(); // Reverse the whole string.
reverseWords(sb, sb.length()); // Reverse each word.
return cleanSpaces(sb, sb.length()); // Clean up the spaces.
}
while (i < n) {
while (i < j || i < n && sb.charAt(i) == ' ') // Skip the spaces.
++i;
while (j < i || j < n && sb.charAt(j) != ' ') // Skip the spaces.
++j;
reverse(sb, i, j - 1); // Reverse the word.
}
}
return -1;
}
}