Tuesday, 26 July 2016

Coding (DSA) All

Write code to check a String is palindrome or not?


public class StringCheckPalindrome {
 
 public static void main(String[] args) {
  System.out.println(checkPalindrome("abc"));
  System.out.println(checkPalindrome("abccba"));
  System.out.println(checkPalindrome("aba"));
  System.out.println(checkPalindrome(""));
 }
 
 static boolean checkPalindrome(String str){
  boolean result=true;
  char[] chars = str.toCharArray();
  
  for(int i=0;i<str.length()/2;i++){
   if(chars[i]!=chars[str.length()-1-i]){
    result=false;
    break;
   }
    
  }
  return result;
  
 }

}


//Write a method which will remove any given character from a String?

public class Solution {

 public static void main(String[] args) {
  System.out.println(removeChar("abcd", 'b'));
  System.out.println(removeChar("babbcbdbb", 'b'));
 }
 
 static String removeChar(String str, char ch){
  String result = null;
  char[] chars = str.toCharArray();
  StringBuilder sb = new StringBuilder();
  for(char ch1: chars){
   if(ch1!=ch){
    sb.append(ch1);
   }
  }
  return sb.toString();
 }
}

No comments:

Post a Comment