Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
If I have
String x = "test";
String s = "tastaegasghet;
you can find t e s t inside the string s. The naive way of doing this with a known string would be something like this:
.*t+.*e+.*s+.*t+.*
This will return true if we can find the letters t e s t in order and any characters inbetween. I want to do the same thing but with two unknown Strings x and s or in otherwords, String s and x can be anything. I don't want something hard coded but something for general use instead.
This is the pseudocode for looping solution:
function (
needle, // x
haystack // s
) {
j = 0
for (i = 0; i < haystack.length && j < needle.length; i++) {
if (haystack[i] == needle[j]) {
j++
}
}
return j == needle.length
}
You only need to loop through each character in haystack string and advance the pointer in needle string when you find a matching character. If the pointer reaches the end of the needle string, it means the needle string can be found as a subsequence of the haystack string.
A small optimization you can do is checking needle.length <= haystack.length before starting the loop.
Just for fun
If you want to go the Cthulhu's way, you can use this construction:
(?>.*?t)(?>.*?e)(?>.*?s)(?>.*?t).*+
This doesn't have the risk of catastrophic backtracking, and should work similar to the loop above (linear complexity), except that it has a lot of overhead compiling and matching the regex.
It's not that hard to just use a loop.
String x = "test";
String s = "tastaegasghet";
int index = 0;
for(int i = 0; i < s.length() && index < x.length(); i++){
if(s.charAt(i) == x.charAt(index)) index++;
}
boolean exists = index == x.length();
System.out.println(exists);
This should be significantly faster than a regex, at least for longer input.
I'd make a simple function, with a loop, instead of a regex. Something like the following:
public boolean containsLetters(string a, string b)
{
char[] aArray = a.toCharArray();
char[] bArray = b.toCharArray();
int lettersFound = 0, lastLocation = 0;
for (int i = 0; i < aArray.length; i++)
{
for (lastLocation=lastLocation; lastLocation < bArray.length; lastLocation++)
{
if (aArray[i] == bArray[lastLocation])
{
lettersFound++;
break;
}
}
}
return lettersFound == aArray.length;
}
The inner for loop stops the first time it finds the letter. It doens't need to determine if it appears more than once since the function returns a boolean, so this saves some time for large strings. It will only return true if it finds them in order. It remembers the index of the last letter it found, and searches through for the next letter from that location.
You can use the Pattern class for this.
String x= "yourValue";
Pattern pattern = Pattern.compile(Mention your pattern here);
Matcher matcher = pattern.matcher(x);
if (matcher.find()) {
System.out.println(matcher.group(0)); //prints /{item}/
} else {
System.out.println("Match not found");
}
Java code without using any built-in function
String s1 = "test";
String s2 = "tastaegasghets";
char ch[] = new char[s1.length()];
char ch1[] = new char[s2.length()];
int k = 0;
for (int i = 0; i < s1.length(); i++) {
ch[i] = s1.charAt(i);
for (int j = 0; j < s2.length(); j++) {
ch1[j] = s2.charAt(j);
if (ch[i] == ch1[j]) {
k++;
break;
}
}
}
if (k == s1.length()) {
System.out.println("true");
} else {
System.out.println("false");
}
Related
class Solution {
public String longestCommonPrefix(String[] strs) {
String result = new String("");
char compareElement;
int i;//index of strs
int j;//index of the first one of string
for(j = 0; j < strs[0].length(); j++){
compareElement = strs[0].charAt(j);
for(i = 1; i < strs.length; i++){
if(compareElement == strs[i].charAt(j)){
if(i == strs.length - 1)
result += compareElement;
else
continue;
}
else{
break;
}
}
}
return result;
}
}
Test sample is
Input: ["flower","flow","flight"]
Output: "fl"
hi there I have got a problem with string in Java in my 4th small program in Leetcode. The aim of this function is to find the longest common prefix string amongst an array of strings. But the exception
Exception in thread "main"
java.lang.StringIndexOutOfBoundsException: String index out of
range: 4
at java.lang.String.charAt(String.java:614)
at Solution.longestCommonPrefix(Solution.java:11)
at __DriverSolution__.__helper__(__Driver__.java:4)
appears over again.
Has someone any idea? Thanks!
I think this is where you go wrong:
if(compareElement == strs[i].charAt(j))
j can become too large as it goes from 0 to strs[0].lenght() (see your outer loop).
If strs[i].lengt() is smaller than strs[0].length() you get an StringIndexOutOfBoundsException.
When you iterate through the comparison strings, you're never checking the length of the string you're comparing. In your example the test case flow. The char at index 4 doesn't exist since only indices 0-3 are defined. if(compareElement == strs[i].charAt(j)){ when j is 4 it'll mess up. In order to fix it you have to make sure you're not going past the length of the string. In addition to that look up what a StringBuilder is, for this small of a test case it won't matter however as you go up larger it will.
Your code fails if you have an element in the array which is shorter than the first element. You need to check that j is still smaller than the length of the string you're comparing:
public String longestCommonPrefix(String[] strs) {
String result = new String("");
char compareElement;
int i;// index of strs
int j;// index of the first one of string
for (j = 0; j < strs[0].length(); j++) {
compareElement = strs[0].charAt(j);
for (i = 1; i < strs.length; i++) {
if (j < strs[i].length() && compareElement == strs[i].charAt(j)) {
if (i == strs.length - 1)
result += compareElement;
else
continue;
} else {
break;
}
}
}
return result;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am doing one simple java code where if
input is : "aabbba"
then
output should be: "a2b3a1"
I have done the below coding but missing somewhere. So let me know my mistake.
public class Test {
public static void main(String[] args) {
String str = "aabbba";
int count = 1;
for (int i = 0; i < str.length(); i = i + count) {
count = 1;
for (int j = i + 1; j < str.length(); j++) {
if (str.charAt(i) == str.charAt(j)) {
count = count + 1;
} else {
System.out.println(str.charAt(i) + "" + count);
break;
}
}//end of inner for
}//end of outer for
}//end of main
}//end of class
Actually you have too much code, You only need one loop, and you should be comparing the letter to the previous one, not attempting to compare each letter to every letter after it.
If you are confused about what your program is doing, the best place to start is to use your debugger to step through the code.
for(int i = 0, count = 1; i < str.length(); i++, count++) {
char ch = str.charAt(i);
char next = i + 1 < str.length() ? str.charAt(i + 1) : (char) -1;
if (ch != next) {
System.out.print("" + ch + count);
count = 0;
}
}
Using your effort and code, you simply did put the print to the wrong place
String str = "aabbba";
int count = 1;
for(int i = 0; i <str.length();i=i+count){
count =1;
for(int j = i+1; j<str.length();j++){
if(str.charAt(i) == str.charAt(j)){
count = count+1;
}
else{
break;
}
}
// Print here otherwise you will miss the last group of letters
// Also if you just want one line use .print instead of println
System.out.print(str.charAt(i)+""+count);
}
Using Java-8 and my StreamEx library it's a one-liner:
String input = "aabbba";
String result = IntStreamEx.ofChars(input).mapToObj(ch -> (char)ch)
.runLengths().join("").joining();
Step-by step:
IntStreamEx.ofChars(input): create IntStreamEx (enhanced IntStream) where each element is the corresponding character of input line.
.mapToObj(ch -> (char)ch): transform to StreamEx<Character> (enhanced Stream<Character>) where each element is the Character object.
.runLengths(): convert to EntryStream<Character, Long> (enhanced Stream<Map.Entry<Character, Long>>) where keys are Character objects and values are counts of equal adjacent characters.
.join(""): convert to StreamEx<String>, joining keys (characters) and values (counts) via given empty separator.
.joining(): final reduction to the resulting string without additional separators.
You're just missing the print of the last group of letters. you only print inside the loop once you found a different letter, you should take into account the last group of letters that has no "different letter" after it
I would suggest using a StringBuilder:
public String myOutput(String str) {
if (str == null || str.length() == 0)
return str;
StringBuilder sb = new StringBuilder();
int count = 1;
char currentChar;
for (int i = 0; i < str.length() - 1; i++) {
currentChar = str.charAt(i);
if (currentChar == str.charAt(i+1)) {
count++;
} else {
sb.append(currentChar);
sb.append(String.valueOf(count));
count = 1;
}
}
sb.append(str.charAt(str.length()-1));
sb.append(String.valueOf(count));
return sb.toString();
}
You only need 1 loop
System.out.println() will cause your output to have line break. You better use System.out.print(). Now your currrent code is resulting :
a2
b3
Hello I am having trouble implementing this function
Function:
Decompress the String s. Character in the string is preceded by a number. The number tells you how many times to repeat the letter. return a new string.
"3d1v0m" becomes "dddv"
I realize my code is incorrect thus far. I am unsure on how to fix it.
My code thus far is :
int start = 0;
for(int j = 0; j < s.length(); j++){
if (s.isDigit(charAt(s.indexOf(j)) == true){
Integer.parseInt(s.substring(0, s.index(j))
Assuming the input is in correct format, the following can be a simple code using for loop. Of course this is not a stylish code and you may write more concise and functional style code using Commons Lang or Guava.
StringBuilder builder = new StringBuilder();
for (int i = 0; i < s.length(); i += 2) {
final int n = Character.getNumericValue(s.charAt(i));
for (int j = 0; j < n; j++) {
builder.append(s.charAt(i + 1));
}
}
System.out.println(builder.toString());
Here is a solution you may like to use that uses Regex:
String query = "3d1v0m";
StringBuilder result = new StringBuilder();
String[] digitsA = query.split("\\D+");
String[] letterA = query.split("[0-9]+");
for (int arrIndex = 0; arrIndex < digitsA.length; arrIndex++)
{
for (int count = 0; count < Integer.parseInt(digitsA[arrIndex]); count++)
{
result.append(letterA[arrIndex + 1]);
}
}
System.out.println(result);
Output
dddv
This solution is scalable to support more than 1 digit numbers and more than 1 letter patterns.
i.e.
Input
3vs1a10m
Output
vsvsvsammmmmmmmmm
Though Nami's answer is terse and good. I'm still adding my solution for variety, built as a static method, which does not use a nested For loop, instead, it uses a While loop. And, it requires that the input string has even number of characters and every odd positioned character in the compressed string is a number.
public static String decompress_string(String compressed_string)
{
String decompressed_string = "";
for(int i=0; i<compressed_string.length(); i = i+2) //Skip by 2 characters in the compressed string
{
if(compressed_string.substring(i, i+1).matches("\\d")) //Check for a number at odd positions
{
int reps = Integer.parseInt(compressed_string.substring(i, i+1)); //Take the first number
String character = compressed_string.substring(i+1, i+2); //Take the next character in sequence
int count = 1;
while(count<=reps)//check if at least one repetition is required
{
decompressed_string = decompressed_string + character; //append the character to end of string
count++;
};
}
else
{
//In case the first character of the code pair is not a number
//Or when the string has uneven number of characters
return("Incorrect compressed string!!");
}
}
return decompressed_string;
}
I'm doing a project for Java 1, and I'm completely stuck on this question.
Basically I need to double each letter in a string.
"abc" -> "aabbcc"
"uk" -> "uukk"
"t" -> "tt"
I need to do it in a while loop in what is considered "Java 1" worthy. So i'm guessing that this means more of a problematic approach.
I know that the easiest way for me to do this, from my knowledge, would be using the charAt method in a while loop, but for some reason my mind can't figure out how to return the characters to another method as a string.
Thanks
[EDIT] My Code (wrong, but maybe this will help)
int index = 0;
int length = str.length();
while (index < length) {
return str.charAt(index) + str.charAt(index);
index++;
}
String s="mystring".replaceAll(".", "$0$0");
The method String.replaceAll uses the regular expression syntax which is described in the documentation of the Pattern class, where we can learn that . matches “any character”. Within the replacement, $number refers to numbered “capturing group” whereas $0 is predefined as the entire match. So $0$0 refers to the matching character two times. As the name of the method suggests, it is performed for all matches, i.e. all characters.
Yeah, a for loop would really make more sense here, but if you need to use a while loop then it would look like this:
String s = "abc";
String result = "";
int i = 0;
while (i < s.length()){
char c = s.charAt(i);
result = result + c + c;
i++;
}
You can do:
public void doubleString(String input) {
String output = "";
for (char c : input.toCharArray()) {
output += c + c;
}
System.out.println(output);
}
Your intuition is very good. charAt(i) will return the character in the string at location i, yes?
You also said you wanted to use a loop. A for loop, traversing the length of the list, string.length(), will allow you to do this. At every single node in the string, what do you need to do? Double the character.
Let's take a look at your code:
int index = 0;
int length = str.length();
while (index < length) {
return str.charAt(index) + str.charAt(index); //return ends the method
index++;
}
Problematically for your code, you are returning two characters immediately upon entering the loop. So for a string abc, you are returning aa. Let's store the aa in memory instead, and then return the completed string like so:
int index = 0;
int length = str.length();
String newString = "";
while (index < length) {
newString += str.charAt(index) + str.charAt(index);
index++;
}
return newString;
This will add the character to newString, allowing you to return the entire completed string, as opposed to a single set of doubled characters.
By the way, this may be easier to do as a for loop, condensing and clarifying your code. My personal solution (for a Java 1 class) would look something like this:
String newString = "";
for (int i = 0; i < str.length(); i++){
newString += str.charAt(i) + str.charAt(i);
}
return newString;
Hope this helps.
try this
String a = "abcd";
char[] aa = new char[a.length() * 2];
for(int i = 0, j = 0; j< a.length(); i+=2, j++){
aa[i] = a.charAt(j);
aa[i+1]= a.charAt(j);
}
System.out.println(aa);
public static char[] doubleChars(final char[] input) {
final char[] output = new char[input.length * 2];
for (int i = 0; i < input.length; i++) {
output[i] = input[i];
output[i + 1] = input[i];
}
return output;
}
Assuming this is inside a method, you should understand that you can only return once from a method. After encountering a return statement, the control goes back to the calling method. Thus your approach of returning char every time in a loop is faulty.
int index = 0;
int length = str.length();
while (index < length) {
return str.charAt(index) + str.charAt(index); // only the first return is reachable,other are not executed
index++;
}
Change your method to build a String and return it
public String modify(String str)
{
int index = 0;
int length = str.length();
String result="";
while (index < length) {
result += str.charAt[index]+str.charAt[index];
index++;
}
return result;
}
I want to count the number of letter, digit and symbol using JAVA
However the result output is not ideal. it should be 5,2,4
but I got 5,2,13
int charCount = 0;
int digitCount = 0;
int symbol = 0;
char temp;
String y = "apple66<<<<++++++>>>";
for (int i = 0; i < y.length(); i++) {
temp = y.charAt(i);
if (Character.isLetter(temp)) {
charCount++;
} else if (Character.isDigit(temp)) {
digitCount++;
} else if (y.contains("<")) {
symbol++;
}
}
System.out.println(charCount);
System.out.println( digitCount);
System.out.println( symbol);
It should be
} else if (temp == '<')) {
symbol++;
}
In your solution, for every non-letter-or-digit character you check if the entire string contains <. This is always true (at least in your example), so the result you get is the number of special characters in the string.
You should use y.charAt(i) == '<' rather than y.contains("<")
if you use y.contains("<"), it uses the whole string to check whether it contains '<' or not. Since String y contains '<'. When in for loop, there are 4 '<', 6 '+' and 3 '>'.
For checking such charraters, y.contains("<") always be true. That is why you get 13 (=4+6+3) for symbol rather than 4.
This bit is wrong:
y.contains("<")
You are checking the whole string each time when you only want to check a single character (temp)
int charCount = 0;
int digitCount = 0;
int symbol = 0;
char temp;
String y = "apple66<<<<++++++>>>";
for (int i = 0; i < y.length(); i++) {
temp = y.charAt(i);
if (Character.isLetter(temp)) {
charCount++;
} else if (Character.isDigit(temp)) {
digitCount++;
****} else if (temp =="<") {
symbol++;
}
}****
else if (y.contains("<")) {
should be
else if (temp == '<') {
because else every time youu have no letter or digit it is raised.
y.contains("<")
seaches for the substring "<" in the string "apple66<<<<++++++>>>" and it always finds it. This happens 13 times which is the number of chars in the substring <<<<++++++>>>" which does contains neither a letter nor a digt.