class Chotu
{
// Returns length of the longest subsequence of 1's
public static int ShortestSequence(String s) {
int count = 0;
int ans=s.length();
for(int i=0;i<s.length();i++)
{
if (s.charAt(i) == '1')
count++;
else
count = 0;
if(count < ans )
ans=count;
}
return ans;
}
// Driver code
public static void main(String[] args)
{
#SuppressWarnings("resource")
Scanner sc=new Scanner(System.in);
String s =sc.next();
if(ShortestSequence(s) > 1)
System.out.println(ShortestSequence(s));
else
System.out.println(-1);
}
}
I'm making program to find shortest sequence of 1's in user input string. I had made program which gives me longest sequence need help.
Input : 11100011001
Output : 1
You can split the String and then use stream:
public static String shortestSequence(String str) {
return Arrays.stream(str.split("[^1]"))
.filter(Predicate.not(String::isBlank))
.sorted(Comparator.comparing(String::length))
.findFirst().orElse("");
}
public static String longestSequence(String str) {
return Arrays.stream(str.split("[^1]"))
.filter(Predicate.not(String::isBlank))
.sorted(Comparator.comparing(String::length).reversed())
.findFirst().orElse("");
}
Then:
String str = "11100011001";
System.out.println("Shortest: " + shortestSequence(str));
System.out.println("Longest: " + longestSequence(str));
Output:
Shortest: 1
Longest: 111
Related
class Palindrome {
// Function to check if a word is
// palindrome
static boolean checkPalin(String word)
{
int n = word.length();
word = word.toLowerCase();
for (int i=0; i<n; i++,n--)
if (word.charAt(i) != word.charAt(n - 1))
return false;
return true;
}
// Function to count palindrome words
static int countPalin(String str)
{
// to check last word for palindrome
str = str + " ";
// to store each word
String word = "";
int count = 0;
for (int i = 0; i < str.length(); i++)
{
char ch = str.charAt(i);
// extracting each word
if (ch != ' ')
word = word + ch;
else {
if (checkPalin(word))
count++;
word = "";
}
}
return count;
}
// Driver code
public static void main(String args[])
{
System.out.println(countPalin("Madam "
+ "Arora teaches malayalam"));
System.out.println(countPalin("Nitin "
+ "speaks malayalam"));
}
}
I only know how to count the number. How can I run through a loop and check every word if it is a palindrome? Can you help me with a method that checks a word and a method that checks a sentence if there are palindrome words? I must use Stacks and Queues. I have done the push, add, remove, dequeue, but I can't check if the input is a sentence.
You need to change only this part
if (checkPalin(word))
{
OutPut = OutPut + word;
}
after for loop return OutPut.
// C# program to count number of
// palindrome words in a sentence
using System;
class Palindrome
{
// Function to check if a word is
// palindrome
public static bool checkPalin(string word)
{
int n = word.Length;
word = word.ToLower();
for (int i = 0; i < n; i++,n--)
{
if (word[i] != word[n - 1])
{
return false;
}
}
return true;
}
// Function to count palindrome words
public static int countPalin(string str)
{
// to check last word for palindrome
str = str + " ";
// to store each word
string word = "";
string Print_Result = "";
int count = 0;
for (int i = 0; i < str.Length; i++)
{
char ch = str[i];
// extracting each word
if (ch != ' ')
{
word = word + ch;
}
else
{
if (checkPalin(word))
{
if (Print_Result == "")
{
Print_Result = word;
}else
{
Print_Result = Print_Result + word;
}
}
word = "";
}
}
return Print_Result;
}
// Driver code
public static void Main(string[] args)
{
Console.WriteLine(countPalin("Madam " +
"Arora teaches math"));
}
}
You could implement a method to return a list of palindrome words after splitting the input string with String.split.
It is convenient to use Java 8 Stream API for such tasks (filter and collect):
import java.util.*;
import java.util.stream.*;
class Palindrome {
// ...
public static List<String> findPalindromes(String str) {
if (null == str || str.isEmpty()) {
return Collections.emptyList();
}
return Arrays.stream(str.split("\\s+")) // split into "words" separated with whitespaces
.filter(Palindrome::checkPalin) // keep the palindrome words
.collect(Collectors.toList()); // get the list from stream
}
// then countPalin() may be refactored as
public static countPalin(String str) {
return findPalindromes(str).size();
}
}
Test
public static void main(String... args) {
String[] data = { null, "", "None",
"Madam Arora teaches malayalam",
"Nitin speaks malayalam"
};
for (String str : data) {
List<String> palindromes = findPalindromes(str);
if (palindromes.isEmpty()) {
System.out.printf("No palindromes found in \"%s\"%n", str);
} else {
System.out.printf("\"%s\" palindromes found in \"%s\"%n", palindromes, str);
}
}
}
Output:
No palindromes found in "null"
No palindromes found in ""
No palindromes found in "None"
"[Madam, Arora, malayalam]" palindromes found in "Madam Arora teaches malayalam"
"[Nitin, malayalam]" palindromes found in "Nitin speaks malayalam"
input is :levelmm
output is: the given string is palindrome because the given string contains level is a palindrome remain character like mm is neglected.
package example;
import java.util.Scanner;
public class exp2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("enter the string");
Scanner scan=new Scanner(System.in);
String s=scan.nextLine();
String t="";
String s1=s.substring(0, s.length()-1);
for(int i=s1.length()-1;i>=0;i--)
{
t=t+s.charAt(i);
}
if(t.equalsIgnoreCase(s1))
{
int count=t.length();
System.out.println("is palindrome"+(count-1));
}else
{
System.out.println("not a palindrome");
}
}
}
but its not working completely..
First of all, the line String s1 = s.substring(0, s.length() - 1); removes one character from your word, which is not something that looks like it's supposed to happen.
What it looks like is that you want to create every possible substring of an input and see if that is a palindrome. To see whether something is a palindrome I propose this:
private static boolean isPalindrome(String word) {
String reverseWord = "";
for (int i = word.length() - 1; i > -1; i--) {
reverseWord += word.toCharArray()[i];
}
return reverseWord.equalsIgnoreCase(word);
}
Getting every single substring is more difficult, but can be done like this:
private static String[] allSubstrings(String word) {
int amount = 0;
for (int i = 0; i < word.length() + 1; i++) {
amount += i;
}
String[] res = new String[amount];
int index = 0;
for (int i = 0; i < word.length(); i++) {
for (int j = i + 1; j < word.length() + 1; j++) {
res[index] = word.substring(i, j);
index++;
}
}
return res;
}
Now, since every word that is 1 long is a palindrome, we don't want that, so in the main method we can say a word has to be more than 1 long. This results in a main method like this:
public static void main(String[] args) {
System.out.println("enter the string");
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
boolean isPal = false;
for (String word : allSubstrings(s)) {
if (word.length() > 1 && isPalindrome(word)) {
isPal = true;
}
}
if (isPal) {
System.out.println("Is palindrome");
} else {
System.out.println("Is not palindrome");
}
}
I hope this answers your question and I wish you happy coding.
public static int countWords(String str)
This method will count the number of words in str
For example, if str = "Hi there", the method would return 2.
I'm a beginner and not supposed to use pre-built programs. I know it probably uses a loop and I need to use .indexOf to find spaces? Something like my failed attempt at the bottom
public static int countWords(String str){
int count=0;
int len=str.length();
if(str.indexOf(" ")>=0){
for(int i=0; i<len; i++)
count=count+i;
}
return count;
You can just write
public static int countWords(String str){
if(str == null){
return 0; // or your wish to return something
}
str = str.trim();
return str.split("\\s+").length;
}
Where \\s+ will split the string even there are around spaces.
The current implementation is completely wrong:
If the string doesn't contain a space, it will not enter the if block, and incorrectly return 0, because that's the initial value of count and it was never changed
If the string contains a space, the loop does not what you want: it sums up the numbers from 0 to len, for example if len = 5, the result will be 0 + 1 + 2 + 3 + 4
There's nothing in the code to account for words. Note that counting the spaces would not be enough, for example consider the input: " Hello there :-) ". Notice the excessive spaces between words, and also at the start and end, and the non-word smiley.
This should be relatively robust:
int countWords(String text) {
String[] parts = text.trim().split("\\W+");
if (parts.length == 1 && parts[0].isEmpty()) {
return 0;
}
return parts.length;
}
The tedious if condition there is to handle some special cases:
empty string
string with only non-word characters
Unit tests:
#Test
public void simple() {
assertEquals(4, countWords("this is a test"));
}
#Test
public void empty() {
assertEquals(0, countWords(""));
}
#Test
public void only_non_words() {
assertEquals(0, countWords("##$#%"));
}
#Test
public void with_extra_spaces() {
assertEquals(4, countWords(" this is a test "));
}
#Test
public void with_non_words() {
assertEquals(4, countWords(" this is a test :-) "));
}
import java.util.Scanner;
public class CountWordsInString {
public static int countWords(String string) {
String[] strArray = string.split(" ");
int count = 0;
for (String s : strArray) {
if (!s.equals("")) {
count++;
}
}
return count;
}
public static void main(String args[]) {
System.out.println("Enter your string: ");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
System.out.println("Total Words: " + countWords(str));
}
}
I am very new to programming and I have to write a method and program for the following; public static String repeat(String str, int n) that returns the string repeated n times. Example ("ho", 3) returns "hohoho" Here is my program so far:
public static void main(String[] args) {
// **METHOD** //
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
String str = in.nextLine();
System.out.println(repeat (str));//Having trouble with this line
}
// **TEST PROGRAM**//
public static String repeat(String str, int n)
{
if (n <= 0)
{
return ""//Having trouble with this line
}
else if (n % 2 == 0)
{
return repeat(str+str, n/2);
}
else
{
return str + repeat(str+str, n/2);
}
}
}
I made some changes to my code, but it still is not working
public static void main(String[] args) {
// **METHOD** //
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
String str = in.nextLine();
int n = in.nextInt();
System.out.println(repeat(str,n));
}
// **TEST PROGRAM**//
public static String repeat(String str, int n)
{
if (n <= 0)
{
return "";
}
else if (n % 2 == 0)
{
return repeat(str+str, n/2);
}
else
{
return str + repeat(str+str, n/2);
}
}
}
You've missed a semi colon on the line you're having trouble with, it should be return ""; and not return ""
Also, the line System.out.println(repeat (str)); should have 2 arguments because you're repeat definition is:
public static String repeat(String str, int n)
As a further note, an easier function might be
public static String repeat(String str, int n)
{
if (n == 0) return "";
String return_str = "";
for (int i = 0; i < n; i++)
{
return_str += str;
}
return return_str;
}
public static String repeat(String toRepeat, int n){
if(n==0){
return "";
}
return toRepeat+repeat(toRepeat,n-1);
}
2 things I noticed quickly: you forgot a semi-column and your call of "repeat" doesn't match the method signature (you forgot n)
You are not passing correct arguments while you calling the desired method.
Call as repeat (str,k) k - should be an integer
I need to find all the palindromes in a string. It takes user input
example: "abbaalla"
it loops through creating a substring that changes as the loop progresses.
example: checks palindrome "a" (true) "ab"(false) "abb" (false) "abba" (true) and so on..
once it reaches the max length of the word it iterates the start of the substring and repeats
example: check palindrome "b" "bb" "bba" and so on..
I need to change the code so that once it finds the first largest palindrome ("abba") the start of the loop will take place after that substring. so the next palindrome should read "alla"
the final output should be a string that includes all palindromes. in this case;
output: "abba alla"
Also this program currently results in: String index out of range: -1
public static String findAllPalindromes(String input){
int indexStart = 0;
int wordMax = input.length();
int wordLength;
String checkPalindrome;
String allPalindromes = "";
for (wordLength = 2; wordLength <= wordMax; wordLength++) {
//creates a substring to check against isAllPalindrome method
checkPalindrome = input.substring(indexStart, wordLength);
//checks checkPalindrome string to see if it is a palindrome
if (isAllPalindrome(checkPalindrome) == true){
allPalindromes += " " + checkPalindrome;
if (checkPalindrome.length() >= allPalindromes.length()){
allPalindromes = checkPalindrome;
}
}
//once program reads string through once, increment index and scan text again
if (wordLength == wordMax && indexStart < wordMax){
indexStart++;
wordLength = 0;
}
}
System.out.println("The palindromes in the text are: ");
System.out.println(allPalindromes);
return allPalindromes;
}
public static Set<CharSequence> printAllPalindromes(String input) {
if (input.length() <= 2) {
return Collections.emptySet();
}
Set<CharSequence> out = new HashSet<CharSequence>();
int length = input.length();
for (int i = 1; i <= length; i++) {
for (int j = i - 1, k = i; j >= 0 && k < length; j--, k++) {
if (input.charAt(j) == input.charAt(k)) {
out.add(input.subSequence(j, k + 1));
} else {
break;
}
}
}
return out;
}
Simple Brute force way-->
public class AllPalindromes {
public static boolean checkPalindrome(String str) {
for(int i=0;i<=str.length()/2;i++)
if(str.charAt(i)!=str.charAt(str.length()-1-i))
return false;
return true;
}
public static void printAllPalindrome(String str) {
for(int i=0;i<=str.length();i++)
for(int j=i;j<str.length();j++)
if(checkPalindrome(str.substring(i,j+1)))
System.out.println(str.substring(i,j+1));
}
public static void main(String[] args) {
printAllPalindrome("abbaalla");
}
}
Here is the solution which displays all palindromes. (Only those palindromes which are of length greater than 3. You can change the if condition inside the loop if you want to print them all.)
Note that #jw23's solution does not display the palindromes which are of even length — only the odd length ones.
public class HelloWorld{
public static void printPalindromes(String s) {
if (s == null || s.length() < 3)
return;
System.out.println("Odd Length Palindromes:");
// Odd Length Palindromes
for (int i=1; i<s.length()-1; i++) {
for (int j=i-1,k=i+1; j>=0 && k<s.length(); j--,k++) {
if (s.charAt(j) == s.charAt(k)) {
if (k-j+1 >= 3)
System.out.println(s.substring(j, k+1) + " with index " +j+ " and "+k);
}
else
break;
}
}
System.out.println("\nEven Length Palindromes:");
// Even Length Palindromes
for (int i=1; i<s.length()-1; i++) {
for (int j=i,k=i+1; j>=0 && k<s.length(); j--,k++) {
if (s.charAt(j) == s.charAt(k)) {
if (k-j+1 >= 3)
System.out.println(s.substring(j, k+1) + " with index " +j+ " and "+k);
}
else
break;
}
}
}
public static void main(String[] args){
String s = "abcbaaabbaa";
printPalindromes(s);
}
}
public class Palindrome
{
static int count=0;
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String s1=sc.next();
String array[]=s1.split("");
System.out.println("Palindromes are :");
for(int i=0;i<=array.length;i++)
{
for(int j=0;j<i;j++)
{
String B=s1.substring(j,i);
verify(B);
}
}
System.out.println("\n"+count);
sc.close();
}
public static void verify(String s1)
{
StringBuilder sb=new StringBuilder(s1);
String s2=sb.reverse().toString();
if(s1.equals(s2))
{
System.out.print(s1+" ");
count++;
}
}
}
My own logic for palindrome program for all substrings
public class Test1 {
public static void main(String[] args) {
String s = "bob";
ArrayList<Character> chr = new ArrayList<Character>();
ArrayList<String> subs= new ArrayList<String>();
for (int i=0;i<s.length();i++)
{
chr.add(s.charAt(i));
}
System.out.println(chr.toString());
StringBuilder subString = new StringBuilder();
for(int i=0; i < s.length();i++)
{
for(int j=i+1;j<s.length();j++)
{
for(int k=i;k<=j;k++)
{
subString.append(chr.get(k));
}
System.out.println(subString.toString());
subs.add(subString.toString());
subString.setLength(0);
}
}
System.out.println(subs);
for(String st : subs)
{
String st2 = new StringBuffer(st).reverse().toString();
if(st.equals(st2))
{
System.out.println(st+" is a palindrome");
}
else
{
System.out.println(st+" not a palindrome");
}
}
}
}
Print All Palindromes in the string
import java.util.*;
class AllPalindroms
{
public static void main(String args[])
{
String input = "abbaalla";
if (input.length() <= 1)
{
System.out.println("Not Palindrome Found.");
}
else
{
int length = input.length();
Set<String> set = new HashSet<String>();
for (int i = 0; i <length; i++)
{
//if(i==0)
for (int j=i+1;j<length+1;j++)
{
String s = input.substring(i, j);
StringBuffer sb = new StringBuffer(s);
sb.reverse();
if(s.equals(sb.toString()) && s.length()>1)
{
set.add(s);
}
}
}
System.out.println(set);
}
}
}
My code to count all palindromes in a string:
import java.util.Scanner;
public class CountPalindromeSapient {
static int count = 0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the given string: ");
String inputStr = sc.nextLine();
countPalindrome(inputStr);
System.out.println("\nTotal count of Palindromes are: "+count);
sc.close();
}
private static int countPalindrome(String inputStr) {
int count = 0;
int len = inputStr.length();
int startIndex =0;
String subString = "";
System.out.println( "Possible substrings are: ");
for (int i = 0; i < len; i++) {
for (int j = startIndex; j <= len; j++) {
subString = inputStr.substring(startIndex, j);
System.out.println(subString);
count = checkPalindrome(subString);
}
startIndex++;
}
return count;
}
private static int checkPalindrome(String subString) {
// TODO Auto-generated method stub
int subLen = subString.length();
boolean isPalindrome = false;
for(int k=0; k<subLen; k++,subLen-- ) { // Important
if (subString.charAt(k) != subString.charAt(subLen -1)) {
isPalindrome = false;
break;
}else {
isPalindrome = true;
}
}
if(isPalindrome == true) {
count ++;
}
return count;
}
}
class StringTest {
public static void main(String[] args) {
StringTest test = new StringTest();
boolean bool = test.checkPalindrom("abbaalla");
if(!bool)
System.out.println("String is not palindrom");
}
private boolean checkPalindrom(String k){
int[] count= new int[k.length()];
boolean[] arr = new boolean[k.length()];
for(int t=0;t<k.length();t++){
int j=0;
char ch = k.charAt(t);
for(int x=t+1;x<k.length();x++){
if(j<count.length){
if(ch == k.charAt(x))
count[j] = x + 1;
else
count[j] = 0;
j++;
}
}
arr[t] = workOnArr(count,t,k);
}
for(int z=0;z<arr.length;z++){
if(arr[z])
return true;
}
return false;
}
private boolean workOnArr(int[] s,int z,String w){
int j = s.length - 1;
while(j -- > 0){
if(s[j] != 0){
if(isPalindrom(w.substring(z, s[j]))){
if(w.substring(z, s[j]).length() > 1){
System.out.println(w.substring(z, s[j]).length());
System.out.println(w.substring(z, s[j]));
}
return true;
}
}
}
return false;
}
private boolean isPalindrom(String s){
int j= s.length() -1;
for(int i=0;i<s.length()/2;i++){
if(s.charAt(i) != s.charAt(j))
return false;
j--;
}
return true;
}
}
output:-
given palindrom are:-
abba, bb, aa, alla, ll
Question: All the palindromes from a word.
public class Test4 {
public static void main(String[] args) {
String a = "ProtijayiMeyeMADAMGiniiniGSoudiptaGina";
allpalindromicsubstrings(a);
}// main
private static void allpalindromicsubstrings(String a) {
Set<String> set = new HashSet<String>();
for (int i = 0; i < a.length(); i++) {
// odd length palindrome
expand(a, i, i, set);
// even length palindrome
expand(a, i, i + 1, set);
} // for
set.parallelStream().filter(words -> words.length() > 1).distinct().forEach(System.out::println);
}// ee
private static void expand(String a, int start, int last, Set<String> set) {
// run till a[start...last] is a palindrome
while (start >= 0 && last <= a.length() - 1 && a.charAt(start) == a.charAt(last)) {
set.add(a.substring(start, last + 1));
// expand in both directions
start--;
last++;
}
}// ee
}
The output palindromes in the word =>
niin
ADA
eye
MADAM
iniini
GiniiniG
ii
MeyeM
ini
Print all the palindromes in a string:
public class test1 {
public static void main(String[] args) {
String a = "Protijayi Meye MADAM GiniiniG Soudipta Gina";
List<String> list = Arrays.stream(a.split(" ")).collect(Collectors.toList());
System.out.println(list);
List<String> plist = new ArrayList<>();
for(int i = 0 ; i <list.size();i++) {
String curr =list.get(i);
if(ispalin(curr)) {plist.add(curr);}
}//for
System.out.println("palindrome list => " +plist);
}//main
private static boolean ispalin(String curr) {
if(curr == null || curr.length() == 0) {return false;}
return new StringBuffer(curr).reverse().toString().equals(curr);
}
}
The output is: palindrome list => [MADAM, GiniiniG]
Another Method in Java 8:
public class B {
public static void main(String[] args) {
String a = "Protijayi Meye MADAM GiniiniG Soudipta Gina";
List<String> list = Arrays.stream(a.split(" ")).collect(Collectors.toList());
// list to stream
// for Multi Threaded environment
Stream<String> stream = list.parallelStream();
// also,Stream<String> stream = list.stream(); for single Threaded environment
long palindrome = stream.filter(B::isPalindrome)// find all palindromes
.peek(System.out::println) // write each match
.count();// terminal - return a count
System.out.println("Count of palindromes: " + palindrome);
// System.out.println("List => " + list);
}
private static boolean isPalindrome(String aa) {
return new StringBuffer(aa).reverse().toString().equals(aa);
}
}
Output:
GiniiniG
MADAM
Count of palindromes: 2
Java program to enter a string and frame a word by joining all the first character of each word.
Display a new word.
import java.util.*;
public class Anshu {
public static void main(String args[]) {
Scanner in = new Scanner(System.in)
System.out.println("Enter a string");
String s = in .nextLine();
char ch = s.charAt(0);
System.out.print(ch);
s = s.toUpperCase;
int l = s.length();
for (int i = 0; i < l; i++)
char a = s.charAt(i);
if (Character.isWhiteSpace())
System.out.print(s.charAt(i + 1) + "");
}
}