I have a String ArrayList consisting alphabets followed by a digit as a suffix to each of the alphabet.
ArrayList <String> baseOctave = new ArrayList();
baseOctave.add("S1");
baseOctave.add("R2");
baseOctave.add("G4");
baseOctave.add("M2");
baseOctave.add("P3");
baseOctave.add("D1");
baseOctave.add("N1");
I pass the strings from this baseOctave and few other characters as input pattern for creating an object.
MyClass obj1 = new MyClass ("S1,,R2.,M2''-");
Since I frequently make use of these kind of input patterns during object instantiation, I would like to use simple characters S, R, G, M etc.
Ex:
MyClass obj1 = new MyClass ("S,,R.,M''-");
MyClass obj2 = new MyClass ("S1,G.,M,D1");
So the alphabets used during object creation may contain digits as suffix or it may not have digit as suffix.
But inside the constructor (or in separate method), I would like to replace these simple alphabets with alphabets having suffix. The suffix is taken from the baseOctave.
Ex: above two strings in obj1 and obj2 should be "S1,,R2.,M2''-" and "S1,G4.,M2,D1"
I tied to do this, but could not continue the code below. Need some help for replacing please..
static void addSwaraSuffix(ArrayList<String> pattern) {
for (int index = 0; index < pattern.size(); index++) {
// Get the patterns one by one from the arrayList and verify and manipulate if necessary.
String str = pattern.get(index);
// First see if the second character in Array List element is digit or not.
// If digit, nothing should be done.
//If not, replace/insert the corresponding index from master list
if (Character.isDigit(str.charAt(1)) != true) {
// Replace from baseOctave.
str = str.replace(str.charAt(0), ?); // replace with appropriate alphabet having suffix from baseOctave.
// Finally put the str back to arrayList.
pattern.set(index, str);
}
}
}
Edited information is below:
Thanks for the answer. I found another solution and works fine. below is the complete code that I found working. Let me know if there is any issue.
static void addSwaraSuffix(ArrayList<String> inputPattern, ArrayList<String> baseOctave) {
String temp = "";
String str;
for (int index = 0; index < inputPattern.size(); index++) {
str = inputPattern.get(index);
// First see if the second character in Array List is digit or not.
// If digit, nothing should be done. If not, replace/insert the corresponding index from master list
// Sometimes only one swara might be there. Ex: S,R,G,M,P,D,N
if (((str.length() == 1)) || (Character.isDigit(str.charAt(1)) != true)) {
// Append with index.
// first find the corresponsing element to be replaced from baseOctave.
for (int index2 = 0; index2 < baseOctave.size(); index2++) {
if (baseOctave.get(index2).startsWith(Character.toString(str.charAt(0)))) {
temp = baseOctave.get(index2);
break;
}
}
str = str.replace(Character.toString(str.charAt(0)), temp);
}
inputPattern.set(index, str);
}
}
I assume that abbreviation is only one character and that in full pattern second character is always digit. Code below relies on this assumptions, so please inform me if they are wrong.
static String replace(String string, Collection<String> patterns) {
Map<Character, String> replacements = new HashMap<Character, String>(patterns.size());
for (String pattern : patterns) {
replacements.put(pattern.charAt(0), pattern);
}
StringBuilder result = new StringBuilder();
for (int i = 0; i < string.length(); i++) {
Character c = string.charAt(i);
char next = i < string.length() - 1 ? string.charAt(i + 1) : ' ';
String replacement = replacements.get(c);
if (replacement != null && (next <= '0' || next >= '9')) {
result.append(replacement);
} else {
result.append(c);
}
}
return result.toString();
}
public static void main(String[] args) {
ArrayList<String> baseOctave = new ArrayList<String>();
baseOctave.add("S1");
baseOctave.add("R2");
baseOctave.add("G4");
baseOctave.add("M2");
baseOctave.add("P3");
baseOctave.add("D1");
baseOctave.add("N1");
System.out.println(replace("S,,R.,M''-", baseOctave));
System.out.println(replace("S1,G.,M,D1", baseOctave));
System.out.println(replace("", baseOctave));
System.out.println(replace("S", baseOctave));
}
Results:
S1,,R2.,M2''-
S1,G4.,M2,D1
S1
Related
Question:
Write a function to find the longest common prefix string among an array of strings. If there is no common prefix, return an empty string "".
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Code:
public class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs==null || strs.length==0)
return "";
for(int i=0;i<strs[0].length();i++) {
char x = strs[0].charAt(i);
for(int j=0;j<strs.length;j++) {
if((strs[j].length()==i)||(strs[j].charAt(i)!=x)) {
return strs[0].substring(0,i);
}
}
}
return strs[0];
}
}
This is the second solution, but I don't understand the inner loop.
I think if the second element in strs returns a string and ends the for loop, the third element will not have a chance to be compared.
You have to check same position in all of the words and just compare it.
positions
word 0 1 2 3 4 5
=====================
w[0] F L O W E R
w[1] F L O W
w[2] F L I G H T
In Java:
class Main {
public static void main(String[] args) {
String[] words = {"dog","racecar","car"};
String prefix = commonPrefix(words);
System.out.println(prefix);
// return empty string
String[] words2 = {"dog","racecar","car"};
String prefix2 = commonPrefix(words2);
System.out.println(prefix2);
// Return "fl" (2 letters)
}
private static String commonPrefix(String[] words) {
// Common letter counter
int counter = 0;
external:
for (int i = 0; i < words[0].length(); i++) {
// Get letter from first word
char letter = words[0].charAt(i);
// Check rest of the words on that same positions
for (int j = 1; j < words.length; j++) {
// Break when word is shorter or letter is different
if (words[j].length() <= i || letter != words[j].charAt(i)) {
break external;
}
}
// Increase counter, because all of words
// has the same letter (e.g. "E") on the same position (e.g. position "5")
counter++;
}
// Return proper substring
return words[0].substring(0, counter);
}
}
Your first loop is itterating over all chars in the first string of array. Second loop is checking char at i posistion of all strings of array. If characters do not match, or length of string is the same as i it returns substring result.
I think the best way to understand is debug this example.
If the char in the second string is different than the char in the first one, then it is correct to return, since it means that the common prefix ends there. Checking the third and following strings is not necessary.
Basically it returns as soon as it finds a mismatch char.
If we first sort them then it would be very easy we have to only go and compare the first and the last element in the vector present there so,
the code would be like,This is C++ code for the implementation.
class Solution {
public:
string longestCommonPrefix(vector<string>& str) {
int n = str.size();
if(n==0) return "";
string ans = "";
sort(begin(str), end(str));
string a = str[0];
string b = str[n-1];
for(int i=0; i<a.size(); i++){
if(a[i]==b[i]){
ans = ans + a[i];
}
else{
break;
}
}
return ans;
}
};
public class Solution {
public string LongestCommonPrefix(string[] strs) {
if(strs.Length == 0)
{
return string.Empty;
}
var prefix = strs[0];
for(int i=1; i<strs.Length; i++) //always start from 1.index
{
while(!strs[i].StartsWith(prefix))
{
prefix = prefix.Substring(0, prefix.Length-1);
}
}
return prefix;
}
}
I facing some issue with write logic for below problem.
I have two ArrayLists of strings:
List1: contains 5 million strings
List2: will create on users input and contains some strings/characters(Ex. a,b,c,g,l,pd,sp,mta)
Now I have to split list1 into multiple Lists according to startsWith strings in list2 like in above case. I need to create 8 lists as starts with 'a', 'b','c', 'g', 'l','pd', 'sp' and 'mta'
But the condition for above is I have to iterate List1 or List2 only once. i.e. worst complexity for algorithm should be size of List1 (5 million).
It is allowed to use collections.sort() method
Code I have tried
// Create List for search strings.
List<String> CharList = new ArrayList<String>();
CharList.add("a");
CharList.add("b");
CharList.add("e");
CharList.add("z");
CharList.add("4");
CharList.add("1");
CharList.add("zi");
List<String> recordList = new ArrayList<String>();
// Creating dummy data with 100 character in live environment it can be
// around 50 lakhs strings
for (int i = 0; i < 100; i++) {
char[] chars = "abcdefghijklmnopqrstuvwxyzABCGDKL0123456789".toCharArray();
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i1 = 0; i1 < 6; i1++) {
char c = chars[random.nextInt(chars.length)];
sb.append(c);
}
String output = sb.toString();
recordList.add(output);
}
// Adding some data mannually
recordList.add("zink");
recordList.add("zebra");
recordList.add("zzzzzz");
Collections.sort(CharList, String.CASE_INSENSITIVE_ORDER);
Collections.sort(recordList, String.CASE_INSENSITIVE_ORDER);
System.out.println("RECORDLIST ===>" + recordList);
System.out.println("***************************************************");
System.out.println("Charlist ===>" + CharList);
System.out.println("***************************************************");
List<List> lists = new ArrayList<List>();
int startIndex = 0, charPointer = 0;
while (startIndex < recordList.size() && charPointer < CharList.size()) {
List<String> temp = new ArrayList<String>();
boolean isHit = false;
String currentRecord = recordList.get(startIndex);
String partitionSattement = CharList.get(charPointer);
while (currentRecord.startsWith(partitionSattement.toUpperCase())
|| currentRecord.startsWith(partitionSattement.toLowerCase())) {
temp.add(recordList.get(startIndex));
isHit = true;
startIndex++;
}
if (!isHit) {
startIndex++;
}
if (!temp.isEmpty()) {
lists.add(temp);
System.out.println(CharList.get(charPointer) + "====>" + temp);
}
charPointer++;
}
Just using the String startsWith method won't work in this case. Consider what happens if the first pattern does not match any input - you'll loop through all strings in the input list without finding a match, even though subsequent pattern matches do exist.
What we need to do instead is compare each pattern against the initial characters of each input string and process accordingly. Let's say we have an input string str and a pattern pat. Let subStr be the first pat.length() characters of str. Now we can compare subStr and pat using the String compareToIgnoreCase method. There are three cases to consider:
subStr < pat Move to the next input string.
subStr == pat Add str to output for pat and move to the next input string.
subStr > pat Move to the next pattern.
Here's some code to illustrate (I've kept your variable names where possible).
List<List<String>> output = new ArrayList<>();
for(int i=0; i<CharList.size(); i++) output.add(new ArrayList<String>());
int startIndex=0;
int charPointer=0;
while(startIndex < recordList.size() && charPointer < CharList.size())
{
String charStr = CharList.get(charPointer);
String recStr = recordList.get(startIndex);
int cmp;
if(recStr.length() < charStr.length())
{
cmp = -1;
}
else
{
String recSubStr = recStr.substring(0, charStr.length());
cmp = recSubStr.compareToIgnoreCase(charStr);
}
if(cmp <= 0)
{
if(cmp == 0) output.get(charPointer).add(recStr);
startIndex++;
}
else
{
charPointer++;
}
}
for(int i=0; i<CharList.size(); i++)
{
System.out.println(CharList.get(i) + " : " + output.get(i));
}
Also, you should note that when you include a pattern that itself starts with another pattern (e.g. "zi" and "z") the longer pattern will never be matched, since the shorter one will capture all inputs.
I can see two problems in your code:
You should remove the following segment:
if (!isHit) {
startIndex++;
}
Actually you don't need that isHit variable at all. If a string doesn't match with a pattern then you still have to compare it with the next pattern.
You should sort the arrays in descending order. As SirRaffleBuffle noted in the other answer you should compare the strings with the longer pattern first. Sorting the strings and patterns in descending order will automatically solve this problem.
I am working on an assignment and this part is tripping me up.
Construct cipher1 by first filling in the matrix with the unique letters from the first key.
For example, if the key is “testkey”, then fill in the key with the letters T, E, S, K, Y.
Do not fill in repeated characters from the key. Then fill the matrix with the remaining characters of the alphabet (again, skipping Q).
Do not repeat any characters that appeared in the key. So, for “testkey”, cipher1 looks like this: "
The cypher is a 5 by 5 array usually filled with the letters of the alphabet minus 'q'.
So if my key is testkey, the cipher will now be filled with "TESKYABCDFGHIJLMNOPRUVWXZ" instead of "ABCDEFGHIJKLMNOPRSTUVWXYZ".
I thought something like this would work but it doesn't.
for (int i = 0; i < key.length(); i++)
{
key.toCharArray();
alphabet.replace(key[i], "");
}
The key variable being a string "TESTKEY" and the alphabet variable also being a string containing "ABCDEFGHIJKLMNOPRSTUVWXYZ".
Looking at it now that code is obviously flawed and now I'm just stuck. Please any one give the suggestion to me
Try this :
public static void main(String[] args) {
String testS = "testkey";
String key = "ABCDEFGHIJKLMNOPRSTUVWXYZ";
testS = testS.toUpperCase() + key;
testS = removeDuplicates(testS);
System.out.println(testS);
}
static String removeDuplicates(String string) {
StringBuilder noDuplicateChars = new StringBuilder();
for (int i = 0; i < string.length(); i++) {
String letter = string.substring(i, i + 1);
if (noDuplicateChars.indexOf(letter) == -1) {
noDuplicateChars.append(letter);
}
}
return noDuplicateChars.toString();
}
If from some reason you don't want to use StringBuilder, you can change the implementation of removeDuplicates to :
static String removeDuplicates(String string) {
String noDuplicates = new String("");
for (int i = 0; i < string.length(); i++) {
if (!noDuplicates.contains("" + string.charAt(i))) {
noDuplicates += "" + string.charAt(i);
}
}
return noDuplicates;
}
You can use LinkedHashSet. In for loop add key characters and in second loop add alphabet characters. Then iterate through set elements and build string.
Note that method add do not place element if it already exist in the set, hence no additional checks are needed.
You just need to use regular expression;
example: 1 - key
input: testkey
code: `String newString = input.replaceAll("(.)\\1{1,}", "$1").toUpperCase();`
output: TESKY
Example 2; Concat newString with the alphapatical string
input: testkey + "ABCDEFGHIJKLMNOPRSTUVWXYZ";
code: `String FinalString = input.replaceAll("(.)\\1{1,}", "$1").toUpperCase();`
output: TESKYABCDFGHIJLMNOPRUVWXZ
I'm trying to find all permutations of a word and add that to an Arraylist and return the array list. But, I believe my recursion is right but, there is a problem with adding the results to the ArrayList.This is what I have so far. The parameters I passed were "eat" and "" and what is returned is "tea" three times
public static ArrayList<String> permutations(String word, String beginning)
{
int l = word.length();
ArrayList<String> temp = new ArrayList<String>();
if(l == 0)
temp.add(beginning + word);
else
{
char c = word.charAt(l-1);
String blah = (beginning + c);
word = word.substring(0, l-1);
for(int i = 0; i < l; i++)
{
permutations(word, blah);
temp.add(blah + word);
}
}
return temp;
}
Probably I didn't have the right idea of your approach to find an easy fix and by the time I got things working I ended up with this. I hope it isn't too much of a departure and that it's still helpful. The output is:
[tea, tae, eta, eat, ate, aet]
import java.util.ArrayList;
public class Perm {
public static void main(String[] args) {
ArrayList<String> perms = new ArrayList<String>();
permutations("tea", perms);
System.out.println(perms);
}
public static ArrayList<String> permutations(String word, ArrayList<String> perms)
{
int l = word.length();
// If the word has only a single character, there is only
// one permutation -- itself. So we add it to the list and return
if (l == 1) {
perms.add(word);
return perms;
}
// The word has more than one character.
// For each character in the word, make it the "beginning"
// and prepend it to all the permutations of the remaining
// characters found by calling this method recursively
for (int i=0; i<word.length(); ++i) {
char beginning = word.charAt(i);
// Create the remaining characters from everything before
// and everything after (but not including) the beginning char
String blah = word.substring(0,i)+word.substring(i+1);
// Get all the permutations of the remaining characters
// by calling recursively
ArrayList<String> tempArray = new ArrayList<String>();
permutations(blah, tempArray);
// Prepend the beginning character to each permutation and
// add to the list
for (String s : tempArray) {
perms.add(beginning + s);
}
}
return perms;
}
}
At input i have some string : "today snowing know " , here i have 3 words , so i must to parse them is such way : every character i must compare with all other characters , and to sum how many same characters these words have , like exemple for "o" letter will be 2 (from "today" and "snowing") or "w" letter will be 2 (from "know" and "snowing"). After that i must to replace these characters with number(transformed in char format) of letters. The result should be "13111 133211 1332".
What i did ?
First i tape some words and
public void inputStringsForThreads () {
boolean flag;
do {
// will invite to input
stringToParse = Input.value();
try {
flag = true;
// in case that found nothing , space , number and other special character , throws an exception
if (stringToParse.equals("") | stringToParse.startsWith(" ") | stringToParse.matches(".*[0-9].*") | stringToParse.matches(".*[~`!##$%^&*()-+={};:',.<>?/'_].*"))
throw new MyStringException(stringToParse);
else analizeString(stringToParse);
}
catch (MyStringException exception) {
stringToParse = null;
flag = false;
exception.AnalizeException();
}
}
while (!flag);
}
I eliminate spaces between words , and from those words make just one
static void analizeString (String someString) {
// + sign treat many spaces as one
String delimitator = " +";
// words is a String Array
words = someString.split(delimitator);
// temp is a string , will contain a single word
temp = someString.replaceAll("[^a-z^A-Z]","");
System.out.println("=============== Words are : ===============");
for (int i=0;i<words.length;i++)
System.out.println((i+1)+")"+words[i]);
}
So i try to compare for every word in part (every word is split in letters) with all letter from all words , But i don know how to count number of same letter and after replace letters with correct number of each letter??? Any ideas ?
// this will containt characters for every word in part
char[] motot = words[id].toCharArray();
// this will containt all characters from all words
char[] notot = temp.toCharArray();
for (int i =0;i<words[i].length();i++)
for (int j=0;j<temp.length ;j++)
{
if (i == j) {
System.out.println("Same word");
}
else if (motot[i] == notot[j] ) {
System.out.println("Found equal :"+lol[i]+" "+lol1[j]);
}}
For counting you might want to use a Map<Character, Integer> counter like java.util.HashMap. If getting a Value(Integer) using a specific key (Character) from counter is 'not null', then your value++ (leverage autoboxing). Otherwise put a new entry (char, 1) in the counter.
Replacing the letters with the numbers should be fairly easy then.
It is better to use Pattern Matching like this:
initially..
private Matcher matcher;
Pattern regexPattern = Pattern.compile( pattern );
matcher = regexPattern.matcher("");
for multiple patterns to match.
private final String[] patterns = new String [] {/* instantiate patterns here..*/}
private Matcher matchers[];
for ( int i = 0; i < patterns.length; i++) {
Pattern regexPattern = Pattern.compile( pattern[i] );
matchers[i] = regexPattern.matcher("");
}
and then for matching pattern.. you do this..
if(matcher.reset(charBuffer).find() ) {//matching pattern.}
for multiple matcher check.
for ( int i = 0; i < matchers.length; i++ ) if(matchers[i].reset(charBuffer).find() ) {//matching pattern.}
Don't use string matching, not efficient.
Always use CharBuffer instead of String.
Here is some C# code (which is reasonably similar to Java):
void replace(string s){
Dictionary<char, int> counts = new Dictionary<char, int>();
foreach(char c in s){
// skip spaces
if(c == ' ') continue;
// update count for char c
if(!counts.ContainsKey(c)) counts.Add(c, 1);
else counts[c]++;
}
// replace characters in s
for(int i = 0; i < s.Length; i++)
if(s[i] != ' ')
s[i] = counts[s[i]];
}
Pay attention to immutable strings in the second loop. Might want to use a StringBuilder of some sort.
Here is a solution that works for lower case strings only. Horrible horrible code, but I was trying to see how few lines I could write a solution in.
public static String letterCount(String in) {
StringBuilder out = new StringBuilder(in.length() * 2);
int[] count = new int[26];
for (int t = 1; t >= 0; t--)
for (int i = 0; i < in.length(); i++) {
if (in.charAt(i) != ' ') count[in.charAt(i) - 'a'] += t;
out.append((in.charAt(i) != ' ') ? "" + count[in.charAt(i) - 'a'] : " ");
}
return out.substring(in.length());
}