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;
}
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 have this method:
public static int parseInt(String str) {
if (isValidNumber(str)) {
int sum = 0;
int position = 1;
for (int i = str.length() - 1; i >= 0; i--) {
int number = str.charAt(i) - '0';
sum += number * position;
position = position * 10;
}
return sum;
}
return -1;
}
which converts a string into a integer. And as you can see it is (at the moment) in a if-statement with a method which checks if the input is a valid input for my purpose:
public static boolean isValidNumber(String str) {
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if(c >= '0' && c <= '9'){
return true;
}
}
return false;
}
I want the string to be number only (negative and positive) no other is allowed. At that time a string i.e 1a1a will be converted to a integer which it shouldn't whereas -1 will not be converted. I think you guys understand what I mean. I don't know how to do that.
Please help!
Try this:
CODE:
public class validNumbers {
public static void main(String[] args) {
System.out.println(parseInt("345"));
System.out.println(parseInt("-345"));
System.out.println(parseInt("a-345"));
System.out.println(parseInt("1a5b"));
}
public static int parseInt(String str) {
String numberWithoutSign = removeSign(str);
if (isValidNumber(numberWithoutSign)) {
int sum = 0;
int position = 1;
for (int i = numberWithoutSign.length() - 1; i >= 0; i--) {
int number = numberWithoutSign.charAt(i) - '0';
sum += number * position;
position = position * 10;
}
if(isNegative(str)){
return -(sum);
}else{
return sum;
}
}
return -1;
}
/**
* Removes sign in number if exists
*/
public static String removeSign(String number){
if(number.charAt(0) == '+' || number.charAt(0) == '-'){
return number.substring(1);
}else{
return number;
}
}
/**
* Determines if a number is valid
*/
public static boolean isValidNumber(String number) {
for (int i = 0; i < number.length(); i++) {
char c = number.charAt(i);
if(c >= '0' && c <= '9'){
continue;
}else{
return false;
}
}
return true;
}
/**
* Determines if a number is negative or not
*/
public static boolean isNegative(String number){
if(number.charAt(0) == '-'){
return true;
}else{
return false;
}
}
}
OUTPUT:
345
-345
-1
-1
To check if a string is a real number you can use a method like this:
public static boolean isInteger(String str) {
try {
Integer.parseInt(str);
return true;
} catch (NumberFormatException nfe) {}
return false;
}
The problem is with your function isValidNumber. It should return a false on first occurrence of a non numeric value, as follows:
public static boolean isValidNumber(String str) {
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if(!(c >= '0' && c <= '9')){
if (i > 0) {
return false;
}
//This will only be invoked when `i == 0` (or less, which is impossible in this for loop), so I don't need to explicitly specify it here, as I have checked for `i > 0` in the above code...
if (c != '-' && c != '+') {
return false;
}
}
}
return true;
}
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
I'm trying to do this:
User inputs a number for example 2013 or 2012 and it checks if the number has any reoccurring digits like in 2012 there is 2 but I don't know where to go from here.
public static boolean hasDuplicates(String text){
for(int i = 0; i < text.length() - 1; i++){
for(int j = i + 1; j < text.length(); j ++){
if(text.charAt(i) == text.charAt(j)){
return true;
}
}
}
return false;
}
You can make it this way:
public static boolean containsDuplicate(int number) {
String strNum = number.toString();
for(int i=0; i < strNum.length() -1 ; i++){
if( containsDuplicatedValue(strNum, strNum.charAt(i) )
return true;
}
return false;
}
private static boolean containsDuplicatedValue(String str, char searchFor) {
return str.indexOf(searchFor) != str.lastIndexOf(searchFor);
}
Here is a way to check for duplicates. If the first occurrence of number has a different index than the last occurrence, then number must occur more than once.
public static boolean containsDuplicate(String str, int number) {
return str.indexOf(number) != str.lastIndexOf(number);
}