I want to search how many times a string appear in another string
It does not work correctly when i put an similar string at the end.
public class C3_Project3_WPr {
public static void main(String[] args) {
String strn1="AliAliAli";
String strn2="AliAliSinaAli";
String strn3="Ali";
int count1=StringCounter(strn1, strn3);
System.out.println(count1);
int count2=StringCounter(strn2, strn3);
System.out.println(count2);
}
//ُString in String Method
static int StringCounter(String str1, String str2){
int counter=0;
if (str1.isEmpty() || str2.isEmpty()) {
return 0;
}
for(int i= 0; i<str1.length(); i++){
if(str1.contains(str2)){
counter++;
str1= str1.substring(str2.length());
}
}
return counter;
}
}
Solution to your problem is here
public static void main(String[] args) {
String strn1 = "AliAliAliwewdwdweAli";
String strn2 = "AliAliSinaAliAlAli";
String strn3 = "Ali";
int count1 = StringCounter(strn1, strn3);
System.out.println(count1);
int count2 = StringCounter(strn2, strn3);
System.out.println(count2);
}
// ُString in String Method
static int StringCounter(String str1, String str2) {
int counter = 0;
if (str1.isEmpty() || str2.isEmpty()) {
return 0;
}
for (int i = str1.indexOf(str2); i >= 0; i = str1.indexOf(str2, i + str2.length())) {
counter++;
}
return counter;
}
}
When modifying str1 you only take in to account the length of the search string, but ignore the index in which it was found. Fixing this (e.g., by using indexOf), will fix your results too:
int index = str1.indexOf(str2);
while (index >= 0) {
counter++;
index = str1.indexOf(str2, index + str2.length());
}
Use recursive method: It's quick and easy way to solve your problem:
static int StringCounter(String str1, String str2){
return (str1.contains(str2)) ? 1 + StringCounter(str1.replaceFirst(str2, ""), str2) : 0;
}
Related
This is my code to count the number of rotations.
But IDK, What is the problem with it.
Can anyone explain and help me out.
Test Case: Input: david vidda
Output: 2
I tried to have brute force approach but, that wasn't working even.
Can anyone point out my mistake??
import java.util.*;
class solution{
public static int arrayLeftRotation(StringBuilder str1, StringBuilder str2)
{
int i;
int count =0;
for (i = 0; i < str1.length(); i++){
if(str1.equals(str2))
{
count++;
str1 = leftRotatebyOne(str1);
System.out.println(str1);
}
else return count;
}
return count;
}
static StringBuilder leftRotatebyOne(StringBuilder str)
{
int i;
char temp = str.charAt(0);
for (i = 0; i < str.length()-1; i++)
str.setCharAt(str.indexOf(str.charAt(i)+""),str.charAt(i+1));
str.setCharAt(i,temp);
return str;
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String strr1= in.nextLine();
StringBuilder str1 = new StringBuilder(strr1);
String strr2 = in.nextLine();
StringBuilder str2 = new StringBuilder(strr2);
System.out.print(arrayLeftRotation(str1, str2));
}
}
Your method leftRotateByOne appears more complicated than necessary.
Try this:
public class Solution
{
public static int arrayLeftRotation(String str1,
String str2)
{
int nr_rotate;
int counter;
nr_rotate = 0;
for (counter = 0; counter < str1.length(); counter++)
{
if (str1.equals(str2))
return (nr_rotate);
else
{
str1 = leftRotateByOne(str1);
nr_rotate++;
System.out.println(str1);
}
}
// No possible solution
return (-1);
} // arrayLeftRotation
public static String leftRotateByOne(String str)
{
return (str.substring(1) + str.charAt(0));
}
public static void main(String[] args)
{
String str1 = "david";
String str2 = "vidda";
System.out.print(arrayLeftRotation(str1, str2));
}
} // class Solution
Another possible solution for arrayLeftRotation,
public static int arrayLeftRotation(String str1, String str2) {
StringBuilder builder = new StringBuilder(str1);
for (int i = 0; i < str1.length(); i++) {
builder.append(str1.charAt(i)).delete(0, 1);
if (str2.equals(builder.toString())) {
return i + 1;
}
}
return -1;
}
Note: this will return -1 if no matches found.
The trick is to append the input string to itself, then call String#indexOf. It will give you the index at which the doubled string contains the expected string, which is what you're looking for.
Example:
public static int numberOfRotations(String input, String expected) {
final String doubledInput = input + input;
return doubledInput.indexOf(expected);
}
If you really want to implement it yourself, you need to simplify your code to minimize the possibility of making mistakes.
public static String rotate(String input) {
return input.substring(1) + input.charAt(0);
}
public static int numberOfRotations(String input, String expected) {
// handle edge cases (null, empty, etc.) here
String rotatedInput = input;
int count = 0;
while (!rotatedInput.equals(expected) && count < input.length()) {
rotatedInput = rotate(rotatedInput);
count++;
}
return count == input.length() ? -1 : count;
}
I am just trying to point out where your error lies and fix it.
Your error lies here in your leftRotatebyOne:
for (i = 0; i < str.length()-1; i++)
str.setCharAt(str.indexOf(str.charAt(i)+""),str.charAt(i+1)); // your error while shifting to the left;
What you are trying to do is shifting one position to the left, and you should just do it as:
for (i = 0; i < str.length()-1; i++)
str.setCharAt(i,str.charAt(i+1));
And then your method will work.
But I have to say Alex M has provided a cleaner solution to your problem. Perhaps you should have a try.
Your solution then can be (after the fix):
public class RotationCount {
public static int arrayLeftRotation(StringBuilder str1, StringBuilder str2) {
int i;
int count = 0;
for (i = 0; i < str1.length(); i++) {
if (!str1.toString().equals(str2.toString())) {
count++;
str1 = leftRotatebyOne(str1);
} else return count;
}
return count;
}
static StringBuilder leftRotatebyOne(StringBuilder str) {
int i;
char temp = str.charAt(0);
for (i = 0; i < str.length() - 1; i++) {
str.setCharAt(i, str.charAt(i + 1));
}
str.setCharAt(i, temp);
return str;
}
public static void main(String[] args) {
StringBuilder str1 = new StringBuilder("david");
StringBuilder str2 = new StringBuilder("vidda");
System.out.print(arrayLeftRotation(str1, str2));
}
}
public static int getNthOccurrence(int n, char find, String str)
{
int counter=0;
for(int i=0;i<str.length();i++)
{
if(str.charAt(i)==find)
{
counter++;
if(counter==n)
return i;
}
}
return -1;
}
I have already seen this thread Java: method to get position of a match in a String?
The code runs that:
int n=getNthOccurrence(3,'n',"you arent gonna find me");
output: 13
You can make a char into a String by simply doing this
String theString = yourChar + "";
Your code could look something like this !spoiler below!
public static int getNthOccurrence(int n, char find, String str)
{
String f = find + "";
int counter = 0;
for (String c : str.split("")){
if (c.equals(f)) n--;
if (n < 1 ) return counter;
counter++;
}
return -1;
}
}
Once you've changed the parameter type to String:
public static int getNthOccurrence(int n, String find, String str)
Use String.indexOf(String, int):
i = -find.length();
for (int count = 0; count < n; ++count) {
i = str.indexOf(find, i + find.length());
if (i < 0) break;
}
return (i >= 0) ? i : -1;
(Note that String.indexOf(char, int) is a preferable way to do it with char, as in the case of the original code).
I'm trying to write the Java code below recursively:
public static int count(String word) {
int numValue = 0;
int length = word.length();
for(int i=0; i<length; i++){
String alpha = "abcdefghijklmnopqrstuvwxyz";
String letter = (word.substring(0 + i,1 + i));
numValue = numValue + alpha.indexOf(letter) + 1;
}
return numValue;
}
public static void main(String[] args) {
System.out.println(count("abc"));
}
The function returns the sum of the index of each letter in the input string parameter.
I'm attempting to write this same code recuersively, can anyone point out where I've gone wrong?
public static int count(int numValue, int i, String word) {
String alpha = "abcdefghijklmnopqrstuvwxyz";
if( i >= word.length()){
return numValue;
}
else{
String letter = (word.substring(0 + i,1 + i));
numValue = numValue + alpha.indexOf(letter) + 1;
count(numValue, i=i+1, word);
}
return numValue;
}
public static void main(String[] args) {
System.out.println(count(0,0, "abc"));
}
A simpler way would be just shrink the string again and again.
public static int count(String word) {
if (word.isEmpty()) {
return 0;
}
final String alpha = "abcdefghijklmnopqrstuvwxyz";
return alpha.indexOf(word.charAt(0)) + count(word.substring(1));
}
To change this function to be recursive, you would ideally use divide and conquer approach which is rather easy to implement. I will present it in a simple and verbose way so that you can see the steps clearly.
public static int count(String word) {
int numValue = 0;
int length = word.length();
if(length > 1)
{
String substring1 = word.substring(0, length/2);
String substring2 = word.subtring(length/2 + 1, length);
numValue += count(substring1);
numValue += count(substring2);
return numValue;
}
else
{
String alpha = "abcdefghijklmnopqrstuvwxyz";
return alpha.indexOf(word) + 1;
}
}
public static void main(String[] args) {
System.out.println(count("abc"));
}
I suppose you are doing this as an exercise to teach yourself recursiveness - if not, you may want to think whether it is not better for you to just use the iterative approach instead of recursiveness.
The variable numValue is of type int. So it doesnt get changed in the calling method, wenn you pass it to another method and change it in there. This means, the line count(numValue, i=i+1, word); basically does nothing.
You can correct the method by returning the result of the recursive call (Since you return in the if, else is not needed):
public static int count(int numValue, int i, String word) {
String alpha = "abcdefghijklmnopqrstuvwxyz";
if( i >= word.length()){
return numValue;
}
String letter = (word.substring(0 + i,1 + i));
numValue = numValue + alpha.indexOf(letter) + 1;
return count(numValue, i=i+1, word);
}
This is the reason, why your function does not work properly. The answer provided by timrau is a nicer solution for the recursion.
I am writing a code to convert a number to binary representation.Here's my code.It doesn't give the correct answer but I can't figure out where I am making the mistake.If someone could point out where my mistake and how to correct it I would be grateful.
public class ConvertBinary{
public static String convertBinary(int n){
String s="";
while(n>0){
s+=(n%2);
n=n/2;
}
int len=s.length();
String[] binary=s.split("");
String[] binaryCopy=new String[s.length()];
for(int i=0;i<len;i++){
binaryCopy[i]=binary[len-i-1];
s+=binaryCopy[i];
}
return s;
}
public static void main (String args[]){
System.out.println(convertBinary(19));
}
}
Apart from all these answers the problem with your code was that you are not clearing the string before reversing it. So before the for loop just put s = "" and you code should work fine.. :)
Based on comment
public class ConvertBinary {
public static String convertBinary(int n) {
String s = "";
while (n > 0) {
s += (n % 2);
n = n / 2;
}
int len = s.length();
String[] binary = s.split("");
String[] binaryCopy = new String[s.length()];
s = "";
for (int i = 0; i < len; i++) {
binaryCopy[i] = binary[len - i - 1];
s += binaryCopy[i];
}
return s;
}
public static void main(String args[]) {
int num = 4;
System.out.println(convertBinary(num));
System.out.println(Integer.toBinaryString(num));
}
}
public static String convertBinary(int n){
String s="";
while(n>0){
s+=(n%2);
n=n/2;
}
return (new StringBuffer(s).reverse().toString());
}
If you're looking for error in your implementation, you'd rather put:
s = (n % 2) + s;
isntead of
s+=(n%2);
so the code'll be
// n should be positive
public static String convertBinary(int n){
if (n == 0)
return "0";
String s = "";
// for is more compact than while here
for (; n > 0; n /= 2)
s = (n % 2) + s;
return s;
}
however in real life
Integer.toString(n, 2);
is much more convenient
Use Java standard library: http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toString%28int,%20int%29
public class ConvertBinary{
public static String convertBinary(int n){
return Integer.toString(n, 2);
}
public static void main (String args[]){
System.out.println(ConveryBinary.convertBinary(19));
}
}
EDIT: As #Holger says, there's also a toBinaryString: http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toBinaryString%28int%29
public static String convertBinary(int n){
return Integer.toBinaryString(n);
}
Hi I've been doing this java program, i should input a string and output the longest palindrome that can be found ..
but my program only output the first letter of the longest palindrome .. i badly need your help .. thanks!
SHOULD BE:
INPUT : abcdcbbcdeedcba
OUTPUT : bcdeedcb
There are two palindrome strings : bcdcb and bcdeedcb
BUT WHEN I INPUT : abcdcbbcdeedcba
output : b
import javax.swing.JOptionPane;
public class Palindrome5
{ public static void main(String args[])
{ String word = JOptionPane.showInputDialog(null, "Input String : ", "INPUT", JOptionPane.QUESTION_MESSAGE);
String subword = "";
String revword = "";
String Out = "";
int size = word.length();
boolean c;
for(int x=0; x<size; x++)
{ for(int y=x+1; y<size-x; y++)
{ subword = word.substring(x,y);
c = comparisonOfreverseword(subword);
if(c==true)
{
Out = GetLongest(subword);
}
}
}
JOptionPane.showMessageDialog(null, "Longest Palindrome : " + Out, "OUTPUT", JOptionPane.PLAIN_MESSAGE);
}
public static boolean comparisonOfreverseword(String a)
{ String rev = "";
int tempo = a.length();
boolean z=false;
for(int i = tempo-1; i>=0; i--)
{
char let = a.charAt(i);
rev = rev + let;
}
if(a.equalsIgnoreCase(rev))
{
z=true;
}
return(z);
}
public static String GetLongest(String sWord)
{
int sLength = sWord.length();
String Lpalindrome = "";
int storage = 0;
if(storage<sLength)
{
storage = sLength;
Lpalindrome = sWord;
}
return(Lpalindrome);
}
}
modified program..this program will give the correct output
package pract1;
import javax.swing.JOptionPane;
public class Palindrome5
{
public static void main(String args[])
{
String word = JOptionPane.showInputDialog(null, "Input String : ", "INPUT", JOptionPane.QUESTION_MESSAGE);
String subword = "";
String revword = "";
String Out = "";
int size = word.length();
boolean c;
String Lpalindrome = "";
int storage=0;
String out="";
for(int x=0; x<size; x++)
{ for(int y=x+1; y<=size; y++)
{ subword = word.substring(x,y);
c = comparisonOfreverseword(subword);
if(c==true)
{
int sLength = subword.length();
if(storage<sLength)
{
storage = sLength;
Lpalindrome = subword;
out=Lpalindrome;
}
}
}
}
JOptionPane.showMessageDialog(null, "Longest Palindrome : " + out, "OUTPUT", JOptionPane.PLAIN_MESSAGE);
}
public static boolean comparisonOfreverseword(String a)
{ String rev = "";
int tempo = a.length();
boolean z=false;
for(int i = tempo-1; i>=0; i--)
{
char let = a.charAt(i);
rev = rev + let;
}
if(a.equalsIgnoreCase(rev))
{
z=true;
}
return(z);
}
}
You have two bugs:
1.
for(int y=x+1; y<size-x; y++)
should be
for(int y=x+1; y<size; y++)
since you still want to go all the way to the end of the string. With the previous loop, since x increases throughout the loop, your substring sizes decrease throughout the loop (by removing x characters from their end).
2.
You aren't storing the longest string you've found so far or its length. The code
int storage = 0;
if(storage<sLength) {
storage = sLength;
...
is saying 'if the new string is longer than zero characters, then I will assume it is the longest string found so far and return it as LPalindrome'. That's no help, since we may have previously found a longer palindrome.
If it were me, I would make a static variable (e.g. longestSoFar) to hold the longest palindrome found so far (initially empty). With each new palindrome, check if the new one is longer than longestSoFar. If it is longer, assign it to longestSoFar. Then at the end, display longestSoFar.
In general, if you're having trouble 'remembering' something in the program (e.g. previously seen values) you have to consider storing something statically, since local variables are forgotten once their methods finish.
public class LongestPalindrome {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String S= "abcdcba";
printLongestPalindrome(S);
}
public static void printLongestPalindrome(String S)
{
int maxBack=-1;
int maxFront = -1;
int maxLength=0;
for (int potentialCenter = 0 ; potentialCenter < S.length();potentialCenter ++ )
{
int back = potentialCenter-1;
int front = potentialCenter + 1;
int longestPalindrome = 0;
while(back >=0 && front<S.length() && S.charAt(back)==S.charAt(front))
{
back--;
front++;
longestPalindrome++;
}
if (longestPalindrome > maxLength)
{
maxLength = longestPalindrome+1;
maxBack = back + 1;
maxFront = front;
}
back = potentialCenter;
front = potentialCenter + 1;
longestPalindrome=0;
while(back >=0 && front<S.length() && S.charAt(back)==S.charAt(front))
{
back--;
front++;
longestPalindrome++;
}
if (longestPalindrome > maxLength)
{
maxLength = longestPalindrome;
maxBack = back + 1;
maxFront = front;
}
}
if (maxLength == 0) System.out.println("There is no Palindrome in the given String");
else{
System.out.println("The Longest Palindrome is " + S.substring(maxBack,maxFront) + "of " + maxLength);
}
}
}
I have my own way to get longest palindrome in a random word. check this out
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println(longestPalSubstr(in.nextLine().toLowerCase()));
}
static String longestPalSubstr(String str) {
char [] input = str.toCharArray();
Set<CharSequence> out = new HashSet<CharSequence>();
int n1 = str.length()-1;
for(int a=0;a<=n1;a++)
{
for(int m=n1;m>a;m--)
{
if(input[a]==input[m])
{
String nw = "",nw2="";
for (int y=a;y<=m;y++)
{
nw=nw+input[y];
}
for (int t=m;t>=a;t--)
{
nw2=nw2+input[t];
}
if(nw2.equals(nw))
{
out.add(nw);
break;
}
}
}
}
int a = out.size();
int maxpos=0;
int max=0;
Object [] s = out.toArray();
for(int q=0;q<a;q++)
{
if(max<s[q].toString().length())
{
max=s[q].toString().length();
maxpos=q;
}
}
String output = "longest palindrome is : "+s[maxpos].toString()+" and the lengths is : "+ max;
return output;
}
this method will return the max length palindrome and the length of it. its a way that i tried and got the answer. and this method will run whether its a odd length or even length.
public class LongestPalindrome {
public static void main(String[] args) {
HashMap<String, Integer> result = findLongestPalindrome("ayrgabcdeedcbaghihg123444456776");
result.forEach((k, v) -> System.out.println("String:" + k + " Value:" + v));
}
private static HashMap<String, Integer> findLongestPalindrome(String str) {
int i = 0;
HashMap<String, Integer> map = new HashMap<String, Integer>();
while (i < str.length()) {
String alpha = String.valueOf(str.charAt(i));
if (str.indexOf(str.charAt(i)) != str.lastIndexOf(str.charAt(i))) {
String pali = str.substring(i, str.lastIndexOf(str.charAt(i)) + 1);
if (isPalindrome(pali)) {
map.put(pali, pali.length());
i = str.lastIndexOf(str.charAt(i));
}
}
i++;
}
return map;
}
public static boolean isPalindrome(String input) {
for (int i = 0; i <= input.length() / 2; i++) {
if (input.charAt(i) != input.charAt(input.length() - 1 - i)) {
return false;
}
}
return true;
}
}
This approach is simple.
Output:
String:abcdeedcba Value:10
String:4444 Value:4
String:6776 Value:4
String:ghihg Value:5
This is my own way to get longest palindrome. this will return the length and the palindrome word
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println(longestPalSubstr(in.nextLine().toLowerCase()));
}
static String longestPalSubstr(String str) {
char [] input = str.toCharArray();
Set<CharSequence> out = new HashSet<CharSequence>();
int n1 = str.length()-1;
for(int a=0;a<=n1;a++)
{
for(int m=n1;m>a;m--)
{
if(input[a]==input[m])
{
String nw = "",nw2="";
for (int y=a;y<=m;y++)
{
nw=nw+input[y];
}
for (int t=m;t>=a;t--)
{
nw2=nw2+input[t];
}
if(nw2.equals(nw))
{
out.add(nw);
break;
}
}
}
}
int a = out.size();
int maxpos=0;
int max=0;
Object [] s = out.toArray();
for(int q=0;q<a;q++)
{
if(max<s[q].toString().length())
{
max=s[q].toString().length();
maxpos=q;
}
}
String output = "longest palindrome is : "+s[maxpos].toString()+" and the lengths is : "+ max;
return output;
}
this method will return the max length palindrome and the length of it. its a way that i tried and got the answer. and this method will run whether its a odd length or even length.