I am suppose to use Boolean to check if the string is palindrome. I'm getting an error, not sure what I am doing wrong. My program already has 3 strings previously imputed by a user. Thank you, I am also using java
public boolean isPalindrome(String word1, String word2, String word3){
int word1Length = word1.length();
int word2Length = word2.length();
int word3Length = word3.length();
for (int i = 0; i < word1Length / 2; i++)
{
if (word1.charAt(i) != word1.charAt(word1Length – 1 – i))
{
return false;
}
}
return isPalindrome(word1);
}
for (int i = 0; i < word2Length / 2; i++)
{
if (word2.charAt(i) != word2.charAt(word2Length – 1 – i))
{
return false;
}
}
return isPalindrome(word2);
}
for (int i = 0; i < word3Length / 2; i++)
{
if (word3.charAt(i) != word3.charAt(word3Length – 1 – i))
{
return false;
}
}
return isPalindrome(word3);
}
// my output should be this
if (isPalindrome(word1)) {
System.out.println(word1 + " is a palindrome!");
}
if (isPalindrome(word2)) {
System.out.println(word2 + " is a palindrome!");
}
if (isPalindrome(word3)) {
System.out.println(word3 + " is a palindrome!");
}
You could do a method for it like this:
First you build a new String and than you check if it is equal.
private static boolean test(String word) {
String newWord = new String();
//first build a new String reversed from original
for (int i = word.length() -1; i >= 0; i--) {
newWord += word.charAt(i);
}
//check if it is equal and return
if(word.equals(newWord))
return true;
return false;
}
//You can call it several times
test("malam"); //sure it's true
test("hello"); //sure it's false
test("bob"); //sure its true
Related
I write this code but I don't know why doesn't work.
static boolean findeText(String text1, String text2) {
char c1[] = text1.toCharArray();
char c2[] = text2.toCharArray();
boolean b = false;
for (int i = 0; i <= c1.length - c2.length; i++) {
for (int j = 0, h = i; j <= c2.length; j++, h++) {
if (i == c2.length) {
return true;
}
if (c1[h] != c2[j]) {
b = false;
break;
}
}
}
return b;
}
I want find text 2 in text 1 and after that return true or false.
if you want to check if some string contains any other string, just use contains() method.
In your case that would be
return text1.contains(text2);
Plus you should always write your code in defensive way. That means you should always make sure there will be no NullPointerException etc. So in your particular case if someone pass either null text1 or null text2, your program will crash.
Above you had NPE in line
if (c1[h] != c2[j])
I have modified your code slightly to get output as requirement.
static boolean findeText(String text1, String text2) {
if ((text1== null) ||(text2==null) || (text1.isEmpty()) || (text2.isEmpty())) {
System.out.println("Invalid input");
return false;
}
char c1[] = text1.toCharArray();
char c2[] = text2.toCharArray();
for (int i = 0; i <= c1.length - c2.length; i++) {
int count = 0;
for (int j = 0; j < c2.length; j++) {
if (c1[i + j] == c2[j]) {
count = count + 1;
}
if (count == c2.length) {
return true;
}
}
}
return false;
}
''Given two string s and t, write a function to check if s contains all characters of t (in the same order as they are in string t).
Return true or false.
recursion not necessary.
here is the snippet of code that I am writing in java.
problem is for input: string1="st3h5irteuyarh!"
and string2="shrey"
it should return TRUE but it is returning FALSE. Why is that?''
public class Solution {
public static String getString(char x)
{
String s = String.valueOf(x);
return s;
}
public static boolean checkSequence(String s1, String s2)
{
String a = getString(s1.charAt(0));
String b = getString(s2.charAt(0));
for (int i = 1; i < s1.length(); i++)
if (s1.charAt(i) != s1.charAt(i - 1))
{
a += getString(s1.charAt(i));
}
for (int i = 1; i < s2.length(); i++)
if (s2.charAt(i) != s2.charAt(i - 1))
{
b += getString(s2.charAt(i));
}
if (!a.equals(b))
return false;
return true;
}
}
This is a solution:
public class Solution {
public static String getString(char x)
{
String s = String.valueOf(x);
return s;
}
public static boolean checkSequence(String s1, String s2)
{
String a = getString(s1.charAt(0));
String b = getString(s2.charAt(0));
int count = 0;
for (int i = 0; i < s1.length(); i++)
{
if (s1.charAt(i) == s2.charAt(count))
{
count++;
}
if (count == s2.length())
return true;
}
return false;
}
}
Each char of String s1 is compared with a char of String s2 at position count,
if they match count increases: count++;
If count has the length of String 2 all chars matched and true is returned.
there are two problems i can see in that code
1 for (int i = 1; i < s1.length(); i++) you are starting from index 1 but string indexes starts from 0
2 if (s1.charAt(i) != s1.charAt(i - 1)) here you are comparing characters of same strings s1 in other loop also this is the case
please fix these first, then ask again
this could be what you are searching for
public class Solution {
public static boolean checkSequence(String s1, String s2) {
for(char c : s2.toCharArray()) {
if(!s1.contains(c+"")) {
return false;
}
int pos = s1.indexOf(c);
s1 = s1.substring(pos);
}
return true;
}
}
Your approach to solve this problem can be something like this :
Find the smaller string.
Initialise the pointer to starting position of smaller string.
Iterate over the larger string in for loop and keep checking if character is matching.
On match increase the counter of smaller pointer.
while iterating keep checking if smaller pointer has reached to end or not. If yes then return true.
Something like this :
public static boolean checkSequence(String s1, String s2)
{
String smallerString = s1.length()<=s2.length() ? s1 : s2;
String largerString = smallerString.equals(s2) ? s1 : s2;
int smallerStringPointer=0;
for(int i=0;i<largerString.length();i++){
if(smallerString.charAt(smallerStringPointer) == largerString.charAt(i)){
smallerStringPointer++;
}
if(smallerStringPointer == smallerString.length()){
return true;
}
}
return false;
}
public static boolean usingLoops(String str1, String str2) {
int index = -10;
int flag = 0;
for (int i = 0; i < str1.length(); i++) {
flag = 0;
for (int j = i; j < str2.length(); j++) {
if (str1.charAt(i) == str2.charAt(j)) {
if (j < index) {
return false;
}
index = j;
flag = 1;
break;
}
}
if (flag == 0)
return false;
}
return true;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String str1 = s.nextLine();
String str2 = s.nextLine();
// using loop to solve the problem
System.out.println(usingLoops(str1, str2));
s.close();
}
I don't think this question is very complicated to an experienced programmer, but I'm pretty new to it so I'm struggling.
I have a list of delimiters declared before a java class as such:
public static final String DELIMITERS = ",<.>/?;:'\"[{]}\\|=+-_)(*&^%$##!`~ \t\n";
I'd like to create a method that takes two parameters (a starting index and a string). The goal is to read through the string and return the next index that corresponds to a character NOT in the list of delimiters given above. If the starting index is a negative number or greater than the length of the text, the method should simply return -1. Otherwise it just returns the index of the next character NOT in the delimiter list.
This is what I have so far:
public static boolean isDelimiter(char c) {
String letter = "" + c;
if(DELIMITERS.contains(letter)){
return true;
}
else{
return false;
}
}
public static int posNextWord(int startPosition, String text) {
boolean isWord = false;
int nextWordPosition = 0;
if(startPosition < 0 || startPosition > (text.length()-1)){
return -1;
}
else{
while(isWord = false) {
for (int i = startPosition; i < text.length(); i++) {
if(!isDelimiter(text.charAt(i))){
nextWordPosition = nextWordPosition + i + startPosition;
isWord = true;
}
else{
isWord = false;
}
}
}
return nextWordPosition;
}
}
}
When I run this program with a sample text and index, however, the method just returns the number 0. Any help at all would be much appreciated. Also, the method isDelimiter is required for use in the posNextWord() method.
This entire block of code is the problem:
while(isWord = false) {
for (int i = startPosition; i < text.length(); i++) {
if(!isDelimiter(text.charAt(i))){
nextWordPosition = nextWordPosition + i + startPosition;
isWord = true;
}
else{
isWord = false;
}
}
}
return nextWordPosition;
First of all, you only need one loop to check each character of your loop. You don't need a while and a for. Second, if you want to find the first non-matching char, you can just return when you find it.
Like this:
for (int i = startPosition; i < text.length(); i++) {
if(!isDelimiter(text.charAt(i))){
return i + startPosition;
}
}
return -1;
See documented comments. Don't hesitate to ask if it is not clear :
public static boolean isDelimiter(char c) {
String letter = "" + c;
if(DELIMITERS.contains(letter)){
return true;
}
//else{ this else is not needed
System.out.println(letter +" is not a delimiter");
return false;
//}
}
public static int posNextWord(int startPosition, String text) {
//boolean isWord = false; not used
int nextWordPosition = 0;
if((startPosition < 0) || (startPosition > (text.length()-1))){
return -1;
}
//else{ this is not needed
//while(isWord = false) {
for (int i = startPosition; i < text.length(); i++) {
if(!isDelimiter(text.charAt(i))){
nextWordPosition = nextWordPosition + i + startPosition;
//isWord = true;
return nextWordPosition; //as Scary Wombat commented
}
//else{
// isWord = false;
//}
}
//isWord = false;
//}
return nextWordPosition;
// }
}
BTW: I don't think it is a good idea to return 0 as "not found" result. 0 may be returned also as valid "found" position.
Problem:
Develop a recursive algorithm to determine if there is a palindrome hidden within a longer word or phrase. A palindrome is a word or phrase that has the same sequence of letters when read from left to right and when read from right to left, ignoring the spaces (e.g., Some like cake, but I prefer pie contains the palindrome I prefer pi).
Below is my code:
public class e125 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int i = 0;
String sLine = "Some like cake, but I prefer pie";
sLine.replaceAll("\\s+", "");
System.out.println(PlainRet(sLine, i));
}
public static String PlainRet(String sLine, int i) {
int nNum;
char c = 0;
String sPlain = "";
if (i >= sLine.length()) {
return "No Plaindrome";
}
c = sLine.charAt(i);
nNum = Isgood(sLine, c, i);
if (nNum != 0) {
for (; i < nNum; i++) {
sPlain += sLine.charAt(i);
}
return sPlain;
}
return PlainRet(sLine, i + 1);
}
public static int Isgood(String sLine, char c, int i) {
for (int j = i + 1; j < sLine.length(); j++) {
if (Character.toUpperCase(sLine.charAt(j)) == Character.toUpperCase(c)) {
if (Isplain(sLine, i, j)) {
return j;
}
}
}
return 0;
}
public static boolean Isplain(String sLine, int i, int j) {
if (Character.toUpperCase(sLine.charAt(j)) != Character.toUpperCase(sLine.charAt(i))) {
return false;
}
else if (i == j || j == i + 1) {
return true;
}
return (Isplain(sLine, i + 1, j - 1));
}
}
I keep getting an output of "I"
I have no idea what is wrong.
Like FatalError commented sLine.replaceAll() returns a new String. You need to reassign sLine or pass the results of the replaceAll() into the method.
You'll find a new error to fix after you do that, but it's just an off-by-one!
I'm trying to implement String method contains() without using the built-in contains() method.
Here is what I have so far:
public static boolean containsCS(String str, CharSequence cs) {
char[] chs = str.toCharArray();
int i=0,j=chs.length-1,k=0,l=cs.length();
//String str = "Hello Java";
// 0123456789
//CharSequence cs = "llo";
while(i<j) {
if(str.charAt(i)!=cs.charAt(k)) {
i++;
}
if(str.charAt(i)==cs.charAt(k)) {
}
}
return false;
}
I was just practicing my algorithm skills and got stuck.
Any advice?
Using Only 1 Loop
I did some addition to Poran answer and It works totally fine:
public static boolean contains(String main, String Substring) {
boolean flag=false;
if(main==null && main.trim().equals("")) {
return flag;
}
if(Substring==null) {
return flag;
}
char fullstring[]=main.toCharArray();
char sub[]=Substring.toCharArray();
int counter=0;
if(sub.length==0) {
flag=true;
return flag;
}
for(int i=0;i<fullstring.length;i++) {
if(fullstring[i]==sub[counter]) {
counter++;
} else {
counter=0;
}
if(counter==sub.length) {
flag=true;
return flag;
}
}
return flag;
}
This should work fine..I am printing execution to help understand the process.
public static boolean isSubstring(String original, String str){
int counter = 0, oLength = original.length(), sLength = str.length();
char[] orgArray = original.toCharArray(), sArray = str.toCharArray();
for(int i = 0 ; i < oLength; i++){
System.out.println("counter at start of loop " + counter);
System.out.println(String.format("comparing %s with %s", orgArray[i], sArray[counter]));
if(orgArray[i] == sArray[counter]){
counter++;
System.out.println("incrementing counter " + counter);
}else{
//Special case where the character preceding the i'th character is duplicate
if(counter > 0){
i -= counter;
}
counter = 0;
System.out.println("resetting counter " + counter);
}
if(counter == sLength){
return true;
}
}
return false;
}
Hints:
Use a nested loop.
Extracting the chars to an array is probably a bad idea. But if you are going to do it, you ought to use it!
Ignore the suggestion to use fast string search algorithms. They are only fast for large scale searches. (If you look at the code for String.indexOf, it just does a simple search ...)
As JB Nizet suggested, here is the actual code for contains():
2123 public boolean contains(CharSequence s) {
2124 return indexOf(s.toString()) > -1;
2125 }
And here is the code for indexOf():
1732 public int indexOf(String str) {
1733 return indexOf(str, 0);
1734 }
Which leads to:
1752 public int indexOf(String str, int fromIndex) {
1753 return indexOf(value, offset, count,
1754 str.value, str.offset, str.count, fromIndex);
1755 }
Which finally leads to:
1770 static int indexOf(char[] source, int sourceOffset, int sourceCount,
1771 char[] target, int targetOffset, int targetCount,
1772 int fromIndex) {
1773 if (fromIndex >= sourceCount) {
1774 return (targetCount == 0 ? sourceCount : -1);
1775 }
1776 if (fromIndex < 0) {
1777 fromIndex = 0;
1778 }
1779 if (targetCount == 0) {
1780 return fromIndex;
1781 }
1782
1783 char first = target[targetOffset];
1784 int max = sourceOffset + (sourceCount - targetCount);
1785
1786 for (int i = sourceOffset + fromIndex; i <= max; i++) {
1787 /* Look for first character. */
1788 if (source[i] != first) {
1789 while (++i <= max && source[i] != first);
1790 }
1791
1792 /* Found first character, now look at the rest of v2 */
1793 if (i <= max) {
1794 int j = i + 1;
1795 int end = j + targetCount - 1;
1796 for (int k = targetOffset + 1; j < end && source[j] ==
1797 target[k]; j++, k++);
1798
1799 if (j == end) {
1800 /* Found whole string. */
1801 return i - sourceOffset;
1802 }
1803 }
1804 }
1805 return -1;
1806 }
I came up with this:
public static boolean isSubString(String s1, String s2) {
if (s1.length() > s2.length())
return false;
int count = 0;
//Loop until count matches needle length (indicating match) or until we exhaust haystack
for (int j = 0; j < s2.length() && count < s1.length(); ++j) {
if (s1.charAt(count) == s2.charAt(j)) {
++count;
}
else {
//Redo iteration to handle adjacent duplicate char case
if (count > 0)
--j;
//Reset counter
count = 0;
}
}
return (count == s1.length());
}
I have recently stumbled upon this problem, and though I would share an alternative solution. I generate all the sub strings with length of the string we looking for, then push them into a hash set and check if that contains it.
static boolean contains(String a, String b) {
if(a.equalsIgnoreCase(b)) {
return true;
}
Set<String> allSubStrings = new HashSet<>();
int length = b.length();
for(int i=0; i<a.length(); ++i) {
if(i+length <= a.length()) {
String sub = a.substring(i, i + length);
allSubStrings.add(sub);
}
}
return allSubStrings.contains(b);
}
public static boolean contains(String large, String small) {
char[] largeArr = large.toCharArray();
char[] smallArr = small.toCharArray();
if (smallArr.length > largeArr.length)
return false;
for(int i = 0 ; i <= largeArr.length - smallArr.length ; i++) {
boolean result = true ;
for(int j = 0 ; j < smallArr.length ; j++) {
if(largeArr[i+j] != smallArr[j]) {
result = false;
break;
}
result = result && (largeArr[i+j]==smallArr[j]);
}
if(result==true) {return true;}
}
return false;
}
Certainly not the most efficient solution due to the nested loop, but it seems to work pretty well.
private static boolean contains(String s1, String s2) {
if (s1.equals(s2)) return true;
if (s2.length() > s1.length()) return false;
boolean found = false;
for (int i = 0; i < s1.length() - s2.length(); i++) {
found = true;
for (int k = 0; k < s2.length(); k++)
if (i + k < s1.length() && s1.charAt(i + k) != s2.charAt(k)) {
found = false;
break;
}
if (found) return true;
}
return false;
}
It can be done using a single loop.
public boolean StringContains(String full, String part) {
long st = System.currentTimeMillis();
if(full == null || full.trim().equals("")){
return false;
}
if(part == null ){
return false;
}
char[] fullChars = full.toCharArray();
char[] partChars = part.toCharArray();
int fs = fullChars.length;
int ps = partChars.length;
int psi = 0;
if(ps == 0) return true;
for(int i=0; i< fs-1; i++){
if(fullChars[i] == partChars[psi]){
psi++; //Once you encounter the first match, start increasing the counter
}
if(psi == ps) return true;
}
long et = System.currentTimeMillis()- st;
System.out.println("StringContains time taken =" + et);
return false;
}