How to use regular expressions in the output +-12aba to +-12 - java

How to use regular expressions in the output +-12aba to +-12, that is, except to a digital and minus symbol so far.
public class LeetCode8 {
public static int myAtoi(String str) {
str = str.replaceAll("\\s+", "");
System.out.println(str);
if (!str.matches("[0-9]+")&&!str.matches("\\+[0-9]+")&&!str.matches("\\-[0-9]+")) {
return 0;
}
str.replaceAll("", "0");
if (str.length() > 10) {
return 0;
}
long a = Long.valueOf(str);
if (a > Integer.MAX_VALUE) {
return 0;
}
return (int) a;
}
public static void main(String[] args) {
int i = myAtoi("-12aba");
System.out.println(i);
//i want wo output -12
}
}

Maybe try this:
private int myAtoi(String input){
Pattern p = Pattern.compile("(\\-|\\+)\\d+");
Matcher m = p.matcher(input);
if (!m.find())
return 0;
else
return Integer.valueOf(m.group());
}

Related

Find all possible string of length k with recursion

For string s = "abcd" ,k=3 then answer should be:
abc
abd
acd
bcd
code by java with recursion(k=3) :
public class SubString {
static ArrayList<String> al = new ArrayList<>();
public static void main(String[] args) {
String s = "abcd";
findsubsequences(s, ""); // Calling a function
for (String subString : al) {
if (subString.length() == 3) {
System.out.println(subString);
}
}
}
public static void findsubsequences(String s, String ans) {
if (s.length() == 0) {
al.add(ans);
return;
}
findsubsequences(s.substring(1), ans + s.charAt(0));
findsubsequences(s.substring(1), ans);
}
}
I want to Find all possible substring of length k in fastest way by recursion and without foreach in arraylist
Solution using backtracking logic (can be generalized to solve any permutation / subsets / combination problems) -
public static void main(String[] args) {
ans = new ArrayList<>();
String s = "abcd";
int k = 3;
generatePermutation(new StringBuilder(""), 0, s.toCharArray(), k);
System.out.println(ans);
}
private static List<String> ans;
private static void generatePermutation(StringBuilder temp, int st, char[] str, int k){
if(temp.length() == k){
// base result
String br = temp.toString();
ans.add(br);
return;
}
for(int i = st; i < str.length; i++){
temp.append(str[i]);
generatePermutation(temp, i + 1, str, k);
temp.setLength(temp.length() - 1);
}
}
Output :
[abc, abd, acd, bcd]
The faster / cleaner solution is to stop iterating when you reached the maximum length. And you should only add elements if the length is correct:
public static void findsubsequences(String s, String ans, int maxLength) {
if (s.length() == 0) {
return;
}
if (ans.length() == maxLength) {
al.add(ans);
return;
}
findsubsequences(s.substring(1), ans + s.charAt(0), maxLength);
findsubsequences(s.substring(1), ans, maxLength);
}
Additionally you could get rid of the static result list ans instead return the results:
public static void main(String[] args) {
String s = "abcdefgh";
List<String> results = findSubsequences(s, "", 3);
for (String subString : results) {
System.out.println(subString);
}
}
public static List<String> findSubsequences(String s, String ans, int maxLength) {
if (s.length() == 0) {
return new ArrayList<>();
}
if (ans.length() == maxLength) {
return Collections.singletonList(ans);
}
List<String> list = new ArrayList<>(findSubsequences(s.substring(1), ans + s.charAt(0), maxLength));
list.addAll(findSubsequences(s.substring(1), ans, maxLength));
return list;
}

Should return how many letters repeated consecutively 3 times in a string,without using regex...use only core concepts

Example :
If I pass "BAAABA" should return 1, as we see that "A" is repeated immediate 3 times.
When I pass "BAABAA" should return 0, as we don't have any letter repeated immediate 3 times.
when I pass "BBBAAABBAA" should return 2.
Code which I have tried so far:
class Coddersclub {
public static void main(String[] args) throws java.lang.Exception {
String input = "Your String";
int result = 0;
int matchingindex = 0;
char[] iteratingArray = input.toCharArray();
for (int matchThisTo = 0; matchThisTo < iteratingArray.length; matchThisTo++) {
for (int ThisMatch = matchThisTo; ThisMatch < iteratingArray.length; ThisMatch++) {
if (matchingindex == 3) {
matchingindex = 0;
result = result + 1;
}
if (iteratingArray[matchThisTo] == iteratingArray[ThisMatch]) {
matchingindex = matchingindex + 1;
break;
} else {
matchingindex = 0;
}
}
}
System.out.println(result);
}
}
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SOTest {
final static String regex = "(\\w)\\1*";
public static void main(String[] args) {
final String inputString = "aaabbcccaaa";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(inputString);
int counter=0;
while (matcher.find()) {
String group = matcher.group(0);
if(group.length()==3) {
counter++;
System.out.println("Group found :: "+group);
}
}
System.out.println("Total pattern count :: "+counter);
}
}
Output:
Group found :: aaa
Group found :: ccc
Group found :: aaa
Total pattern count :: 3
Since you've tagged this question with C#, here's a C# solution:
public static int CountTriples(string text)
{
int count = 0;
for (int i = 0; i < text.Length - 2; ++i)
{
if (text[i] == text[i+1] && text[i] == text[i+2])
{
++count;
i += 2;
}
}
return count;
}
[EDIT]
Someone other than the OP has removed the C# tag that was there when I wrote this answer. I'll leave this here anyway, since the code is trivially convertible to Java.

Search and get equal characters in a String

I need to search for a certain String in another character-by-character string and if the characters are the same get such a character;
I'm doing it this way
public String searchForSignature(String texto2) throws NoSuchAlgorithmException {
String myString = "", foundString = "";
myString = "aeiousrtmvb257";
for (int i = 0; i < texto2.length() || i <= 1000; i++) {
char c = texto2.charAt(i);
for (int j = 0; j < myString.length(); j++) {
if (c == myString.charAt(j)) {
foundString = foundString + c;
}
}
}
return foundString;
}
I would like to improve the performance and saw that there are forms and using regular expressions, as I am still a little lay I could not succeed in the way I did.
public String searchForSignature2(String texto2) {
Pattern pattern = Pattern.compile("aeiousrtmvb257");
Matcher matcher = pattern.matcher(texto2);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
return matcher.group(1).toString();
}
Does not return anything
//edit
Really, I guess I was not very clear on the question.
Actually I need to get all the characters equal to "aeiousrtmvb257" the ones that are in the String
I did it that way, now it seems OK, I just do not know if the performance is satisfactory.
public String searchForSignature2(String texto2) {
String foundString = "";
Pattern pattern = Pattern.compile("[aeiousrtmvb257]");
Matcher matcher = pattern.matcher(texto2);
while (matcher.find()) {
System.out.println(matcher.group());
foundString+=matcher.group();
}
return foundString;
}
}
As far as I understood your question, by using Patternand Matcher this should do the trick:
Code
private static final String PATTERN_TO_FIND = "[aeiousrtmvb257]";
public static void main(String[] args) {
System.out.println(searchForSignature2("111aeiousrtmvb257111"));
}
public static String searchForSignature2(String texto2) {
Pattern pattern = Pattern.compile(PATTERN_TO_FIND);
Matcher matcher = pattern.matcher(texto2);
StringBuilder result = new StringBuilder();
while (matcher.find()) {
result.append(matcher.group());
}
return result.toString();
}
Output
aeiousrtmvb257
I don't know what was the reason behind texto2.length() || i <= 1000, but based on the logic in your method, I could suggest the below solution:
public static void main(String... args) throws IOException {
System.out.println(searchForSignature("hello"));
}
public static String searchForSignature(String texto2) {
String myString = "aeiousrtmvb257";
StringBuilder builder = new StringBuilder();
for (char s : texto2.toCharArray()) {
if (myString.indexOf(s) != -1) {
builder.append(s);
}
}
return builder.toString();
}
Output: eo
I don't get it, why would you print the string that you found
public static String searchForSignature2(String texto2) {
String maaString = "aeiousrtmvb257";
String toSearch = ".*" + maaString +".*";
boolean b = Pattern.matches(toSearch, texto2);
return b ? maaString : "";
}
public static void main(String[] args)
{
String input = "4erdhrAW BLBAJJINJOI WETSEKMsef saemfosnens3bntu is5o3n029j29i30kwq23eki4"+
"maoifmakakmkakmsmfajiwfuanyi gaeniygaenigaenigeanige anigeanjeagjnageunega"+
"movmmklmklzvxmkxzcvmoifsadoi asfugufngs"+
"wpawfmaopfwamopfwampfwampofwampfawmfwamokfesomk"+
"3rwq3rqrq3rqetgwtgwaeiousrtmvb2576266wdgdgdgdgd";
String myString = searchForSignature2(input);
System.out.println(myString);
}
you need to add .* to tell that your string is surrounded by any char

Using StringBuilder getting null as output

I am doing one coding question in which I try to decrypt the input string. The procedure for the decryption is:
from 0 to 9 it represent alphabets from a to i.
then 10# represent j, 11# represent k and so.
import java.util.HashMap;
public class Julia {
public static void main(String[] args) {
String s="10#21#12#91";
Julia obj=new Julia();
String result=obj.decrypt(s);
System.out.println(result);
}
public String decrypt(String msg)
{
HashMap<String,Character> hs=new HashMap<>();
hs.put("1",'a');
hs.put("2",'b');
hs.put("3",'c');
hs.put("4",'d');
hs.put("5",'e');
hs.put("6",'f');
hs.put("7",'g');
hs.put("8",'h');
hs.put("9",'i');
hs.put("10",'j');
hs.put("11",'k');
hs.put("12",'l');
hs.put("13",'m');
hs.put("14",'n');
hs.put("15",'o');
hs.put("16",'p');
hs.put("17",'q');
hs.put("18",'r');
hs.put("19",'s');
hs.put("20",'t');
hs.put("21",'u');
hs.put("22",'v');
hs.put("23",'w');
hs.put("24",'x');
hs.put("25",'y');
hs.put("26",'x');
StringBuilder n=new StringBuilder();
for(int i=msg.length()-1;i>=0;i--)
{
if(msg.charAt(i)=='#' && i>=2)
{
StringBuilder s=new StringBuilder().append(msg.charAt(i-2)).append(msg.charAt(i-1));
System.out.println(s);
n.append(hs.get(s));
System.out.println(n);
i=i-2;
}
else
{
n.append(hs.get(msg.charAt(i)));
}
}
return n.toString();
}
}
That is code I wrote. But the output I am getting is nullnullnullnullnull.
I think the issue is with StringBuilder. Can anyone help me with that and explain the concept? If someone has better solution please guide.
You should not use data (a map) when you could have used a simple formula.
My suggestion:
import java.util.ArrayList;
import java.util.List;
public final class Julia {
public static void main(final String[] args) {
final String s = "10#21#12#91";
final String result = decrypt(s);
System.out.println(result);
}
private static String decrypt(final String s) {
final List<Integer> crypt = new ArrayList<>();
final String[] groups = s.split("#");
for (int i = 0; i < groups.length; i++) {
final String group = groups[i];
int j = 0;
// Special case for last group
if ((i == (groups.length - 1)) && !s.endsWith("#")) {
j = group.length();
}
if (group.length() > 2) {
j = group.length() - 2;
}
for (int k = 0; k < j; k++) {
crypt.add(Integer.valueOf(group.substring(k, k + 1)));
}
if (j < group.length()) {
crypt.add(Integer.valueOf(group.substring(j, group.length())));
}
}
final StringBuilder n = new StringBuilder(crypt.size());
for (final Integer c : crypt) {
final char d = (char) (('a' + c) - 1);
n.append(d);
}
return n.toString();
}
}
Please note that there are two mistakes in the question: The letter a is 1, not zero, and the value for 26 is z, not x. The latter error is typical when you use data where a formula would do.
Since you are learning, I would note that the decrypt methods - both my suggestion and yours - should be static since they do not use any fields, so the instantiation is not necessary.
This is Pattern Matching problem which can be solved by Regex.
Your code has some bugs and those are already pointed out by others. I don't see any solution which looks better than a simple regex solution.
Below regex code will output 'julia' for input '10#21#12#91'.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Julia {
public static void main(String[] args) {
String s="10#21#12#91";
Julia obj=new Julia();
String result=obj.decrypt(s);
System.out.println(result);
}
public String decrypt(String msg)
{
Pattern regex = Pattern.compile("((\\d\\d#)|(\\d))");
Matcher regexMatcher = regex.matcher(msg);
StringBuffer result = new StringBuffer();
while (regexMatcher.find())
regexMatcher.appendReplacement(result, getCharForNumber(Integer.parseInt(regexMatcher.group(1).replace("#",""))));
return result.toString();
}
private String getCharForNumber(int i) {
return i > 0 && i < 27 ? String.valueOf((char)(i + 96)) : null;
}
}
I hope it helps.
hs.get(s) will always return null, since s is not a String.
Try hs.get(s.toString())
hs.get(msg.charAt(i)) will also always return null, since you are passing a char to get instead of String.
There may also be logic problems in your code, but it's hard to tell.
Optimized version of your code
public class Main {
public static void main(String[] args) {
String cipher = "10#21#12#91";
System.out.print(decrypt(cipher));
//output : julia
}
static String decrypt(String cipher) {
//split with # to obtain array of code in string array
String[] cipher_char_codes = cipher.split("#");
//create empty message
StringBuilder message = new StringBuilder();
//loop for each code
for (String code : cipher_char_codes) {
//get index of character
int index = Integer.parseInt(code);
if (index > 26) {
char[] pair = code.toCharArray();
for (int i = 0; i < pair.length; i++) {
int x = Integer.parseInt("" + code.charAt(i));
message.append((char) ('a' + ((x - 1) % 26)));
}
} else {
//map index into 1 to 26
//find ascii code and cast into char
message.append((char) ('a' + ((index - 1) % 26)));
}
}
return message.toString();
}
}
Regex is indeed the way to go, and the code proposed by Pirate_Jack can be improved. It calls the expensive regex two superfluous times (replace is a regex operation).
Following is a yet improved version:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public final class Julia3 {
public static void main(final String[] args) {
final String s = "10#21#12#91";
final String result = decrypt(s);
System.out.println(result);
}
public static String decrypt(final String msg) {
final Pattern regex = Pattern.compile("((\\d\\d)(#)|(\\d))");
final Matcher regexMatcher = regex.matcher(msg);
final StringBuffer result = new StringBuffer();
String c;
while (regexMatcher.find()) {
if (regexMatcher.group(2) == null) {
c = regexMatcher.group(1);
} else {
c = regexMatcher.group(2);
}
result.append((char) ((Integer.parseInt(c) + 'a') - 1));
}
return result.toString();
}
}
This is not right :
hs.get(s)
s is a StringBuilder. It should be hs.get(Char)
Edit: an optional different solution:
public class Julia {
public static void main(String[] args) {
String s="10#21#12#91";
List<String> numbers = splitToNumbers(s);
Julia obj=new Julia();
String result=obj.decrypt(numbers);
System.out.println(result);
}
/**
*#param s
*#return
*/
private static List<String> splitToNumbers(String s) {
//add check s is not null
char[] chars = s.toCharArray();
char delimiter = '#';
List<String> numberAsStrings = new ArrayList<String>();
int charIndex = 0;
while (charIndex < (chars.length -3)) {
char theirdChar = chars[charIndex+2];
if(theirdChar == delimiter) {
numberAsStrings.add(""+chars[charIndex]+chars[charIndex+1]);
charIndex +=3;
}else {
numberAsStrings.add(""+chars[charIndex]);
charIndex ++;
}
}
//add what's left
while (charIndex < chars.length) {
numberAsStrings.add(""+chars[charIndex]);
charIndex++;
}
return numberAsStrings;
}
public String decrypt(List<String> numbersAsStings){
StringBuilder sb=new StringBuilder();
for (String number : numbersAsStings) {
int num = Integer.valueOf(number);
sb.append(intToChar(num-1));
}
return sb.toString();
}
private char intToChar(int num) {
if((num<0) || (num>25) ) {
return '?' ;
}
return (char)('a' + num);
}
}

Extracting Ints from Strings in Java

I'm trying to write a method which takes a String, looks for Ints in it
and then adds them together.
for example:
String s = "five5six66"
should return 5+66 = 71 or:
String s = "1ciao2three3"
should return 1+2+3 = 6
The following is what I wrote already, but when I run it I get a
NumberFormatException
code (Update 1):
public static int addNumbers(String s) {
String numbers="";
int addNumbers = 0;
int i;
char c;
for (i=0; i<s.length(); i++) {
if (s.charAt(i)>='0' && s.charAt(i)<='9') {
c = s.charAt(i);
while (i<s.length()-1) {
if (s.charAt(i+1)>='0' && s.charAt(i+1)<='9')
numbers = numbers.valueOf(c + s.charAt(i+1));
addNumbers = addNumbers + Integer.parseInt(numbers);
}
addNumbers = addNumbers + Character.getNumericValue(c);
}
}
return addNumbers;
}
Hopefully you can help me fix this code and please, let me understand what I did wrong!
Also can I expand it so if I have a String like:
String s = "hi123and27"
I can get 123+27 = 150?
Because my code is limited to a 2 digit number as it is now.
I would suggest using REGEX to address your requirements:
you will need:
the REGEX pattern: "\d+"
an accumulator that is concatenating the value you get of the given String
Example:
public static void main(String[] args) {
String s = "hi123and27";
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(s);
int accumulator = 0;
while (m.find()) {
accumulator += Integer.parseInt(m.group());
}
System.out.println("final result: " + accumulator );
}
Regex + Java 8 streams:
public static int addNumbers(String str) {
return Arrays.stream(str.replaceAll("[^0-9]", " ").split(" "))
.filter(s -> !s.isEmpty())
.mapToInt(Integer::parseInt)
.sum();
}
EDIT regarding recommendations is the comments:
public static int addNumbers(String str) {
return Arrays.stream(str.split("[^0-9]+"))
.filter(s -> !s.isEmpty())
.mapToInt(Integer::parseInt)
.sum();
}
Try this
public static void main(String [] args){
String string = "hi123and27";
int size = string.length();
int sum = 0;
StringBuilder val = new StringBuilder();
for (int idx = 0; idx < size; idx++) {
Character character = string.charAt(idx);
if (Character.isDigit(character)) {
val.append(character);
//if last character is a digit
if((idx+1 == size) && val.length() > 0)
sum += Integer.parseInt(val.toString());
}else{
if(val.length() > 0)
sum += Integer.parseInt(val.toString());
//reset the val for digits between characters for it to store the next sequence
val.setLength(0);
}
}
System.out.println("The sum is : " + sum);
}
You should try this one.
public static int addNum(String text){
String numbers = "";
int finalResult = 0;
for(int i=0;i < text.length();i++){
if(isNumeric(text.substring(i, i + 1)))
{
numbers += text.substring(i, i + 1);
if(i==text.length()-1) {
finalResult += Integer.parseInt(numbers);
}
}else {
if(!numbers.equals("")){
finalResult += Integer.parseInt(numbers);
numbers = "";
}
}
}
return finalResult;
}
public static boolean isNumeric(String str)
{
try{
int d = Integer.parseInt(str);
}
catch(NumberFormatException ex){
return false;
}
return true;
}

Categories

Resources