Find a palindrome in a string [duplicate] - string

This question already has answers here:
Check string for palindrome
(42 answers)
Closed 5 years ago.
I get a String and if that String contains a palindrome i have to return the palindrome. For example : "hsjwiUHUkajs" should return UHU, "hjakhdANNAjhad" should return ANNA.
How can I do that?
public static void main(String [] args) {
string s = "anna";
for(int i = 0; i<s.length; i++;) {
}
}

The way is explode all characters in a array.
Make a var with start at 1.
Make a for with compare 1# and #3 char.
Ex: a#a (# = 2# position).
If 1# = #3 then palindromo.
If not compare #2 = #3
If equal compare 1# = 4#
If equal palindromo.
If not them inclement start at 2.
Loop at for and compare 2# and #4
3# and #5

Related

why 1 and a retuned 1 are the same object [duplicate]

This question already has answers here:
Dart int and double being interned? Treated specially by identical()?
(3 answers)
Closed 1 year ago.
I'm confused,,who can explan it to me ,my code:
int fun1() {
return 1;
}
int fun2(int x) {
return x + x;
}
void main() {
print(identical(1, fun1()));
print(identical(2, fun2(1)));
}
result:
true
true
my question:
why const 1 and fun1() are the same object
const 2 and fun2() are the same object ?? thanks
It's because you executed fun1() which returned 1 and now you comparing 1 and 1 which is obviously true and true.

Im trying to sort a string in js. but im missing saomething [duplicate]

This question already has answers here:
Sorting in JavaScript: Shouldn't returning a boolean be enough for a comparison function?
(2 answers)
Closed 2 years ago.
function sortStrings(stringList) {
var retval = "";
var strings = stringList.split(',');
var sortedStrings = strings.sort((a,b) => {
return a < b;
});
sortedStrings.forEach((str) => {
retval = str + ',';
} );
return retval;
}
what mistake am I making
Your compare function has an error. The logical operator < only returns either true or false while the compare is expected to return an integer. Integers <0 mean that a < b, integers =0 mean a == b and integers >0 mean that a > b.
To accomplish that with strings, you should use localeCompare:
return a.localeCompare(b)

Determine if the integer is one digit and add a zero before it [duplicate]

This question already has answers here:
Leading zeros for Int in Swift
(12 answers)
Closed 7 years ago.
I need to check if the int is only one digit and if it is, I want to add a zero in front of it. I have this code but it doesnt work.
var minutes2 = Int(minutes)
var minutessize: Int = sizeofValue(minutes2)
if minutessize < 2 {
var needStringHere = "0\(minutes2)"
let a: Int? = needStringHere.toInt()
minutes2 = a!
}
You can just check if the minutes count is less than 10:
var str = "\(minutes2)"
if (minutes2 < 10) { str = "0\(minutes2)" }

Sorting a string using another sorting order string [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I saw this in an interview question ,
Given a sorting order string, you are asked to sort the input string based on the given sorting order string.
for example if the sorting order string is dfbcae
and the Input string is abcdeeabc
the output should be dbbccaaee.
any ideas on how to do this , in an efficient way ?
The Counting Sort option is pretty cool, and fast when the string to be sorted is long compared to the sort order string.
create an array where each index corresponds to a letter in the alphabet, this is the count array
for each letter in the sort target, increment the index in the count array which corresponds to that letter
for each letter in the sort order string
add that letter to the end of the output string a number of times equal to it's count in the count array
Algorithmic complexity is O(n) where n is the length of the string to be sorted. As the Wikipedia article explains we're able to beat the lower bound on standard comparison based sorting because this isn't a comparison based sort.
Here's some pseudocode.
char[26] countArray;
foreach(char c in sortTarget)
{
countArray[c - 'a']++;
}
int head = 0;
foreach(char c in sortOrder)
{
while(countArray[c - 'a'] > 0)
{
sortTarget[head] = c;
head++;
countArray[c - 'a']--;
}
}
Note: this implementation requires that both strings contain only lowercase characters.
Here's a nice easy to understand algorithm that has decent algorithmic complexity.
For each character in the sort order string
scan string to be sorted, starting at first non-ordered character (you can keep track of this character with an index or pointer)
when you find an occurrence of the specified character, swap it with the first non-ordered character
increment the index for the first non-ordered character
This is O(n*m), where n is the length of the string to be sorted and m is the length of the sort order string. We're able to beat the lower bound on comparison based sorting because this algorithm doesn't really use comparisons. Like Counting Sort it relies on the fact that you have a predefined finite external ordering set.
Here's some psuedocode:
int head = 0;
foreach(char c in sortOrder)
{
for(int i = head; i < sortTarget.length; i++)
{
if(sortTarget[i] == c)
{
// swap i with head
char temp = sortTarget[head];
sortTarget[head] = sortTarget[i];
sortTarget[i] = temp;
head++;
}
}
}
In Python, you can just create an index and use that in a comparison expression:
order = 'dfbcae'
input = 'abcdeeabc'
index = dict([ (y,x) for (x,y) in enumerate(order) ])
output = sorted(input, cmp=lambda x,y: index[x] - index[y])
print 'input=',''.join(input)
print 'output=',''.join(output)
gives this output:
input= abcdeeabc
output= dbbccaaee
Use binary search to find all the "split points" between different letters, then use the length of each segment directly. This will be asymptotically faster then naive counting sort, but will be harder to implement:
Use an array of size 26*2 to store the begin and end of each letter;
Inspect the middle element, see if it is different from the element left to it. If so, then this is the begin for the middle element and end for the element before it;
Throw away the segment with identical begin and end (if there are any), recursively apply this algorithm.
Since there are at most 25 "split"s, you won't have to do the search for more than 25 segemnts, and for each segment it is O(logn). Since this is constant * O(logn), the algorithm is O(nlogn).
And of course, just use counting sort will be easier to implement:
Use an array of size 26 to record the number of different letters;
Scan the input string;
Output the string in the given sorting order.
This is O(n), n being the length of the string.
Interview questions are generally about thought process and don't usually care too much about language features, but I couldn't resist posting a VB.Net 4.0 version anyway.
"Efficient" can mean two different things. The first is "what's the fastest way to make a computer execute a task" and the second is "what's the fastest that we can get a task done". They might sound the same but the first can mean micro-optimizations like int vs short, running timers to compare execution times and spending a week tweaking every millisecond out of an algorithm. The second definition is about how much human time would it take to create the code that does the task (hopefully in a reasonable amount of time). If code A runs 20 times faster than code B but code B took 1/20th of the time to write, depending on the granularity of the timer (1ms vs 20ms, 1 week vs 20 weeks), each version could be considered "efficient".
Dim input = "abcdeeabc"
Dim sort = "dfbcae"
Dim SortChars = sort.ToList()
Dim output = New String((From c In input.ToList() Select c Order By SortChars.IndexOf(c)).ToArray())
Trace.WriteLine(output)
Here is my solution to the question
import java.util.*;
import java.io.*;
class SortString
{
public static void main(String arg[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
// System.out.println("Enter 1st String :");
// System.out.println("Enter 1st String :");
// String s1=br.readLine();
// System.out.println("Enter 2nd String :");
// String s2=br.readLine();
String s1="tracctor";
String s2="car";
String com="";
String uncom="";
for(int i=0;i<s2.length();i++)
{
if(s1.contains(""+s2.charAt(i)))
{
com=com+s2.charAt(i);
}
}
System.out.println("Com :"+com);
for(int i=0;i<s1.length();i++)
if(!com.contains(""+s1.charAt(i)))
uncom=uncom+s1.charAt(i);
System.out.println("Uncom "+uncom);
System.out.println("Combined "+(com+uncom));
HashMap<String,Integer> h1=new HashMap<String,Integer>();
for(int i=0;i<s1.length();i++)
{
String m=""+s1.charAt(i);
if(h1.containsKey(m))
{
int val=(int)h1.get(m);
val=val+1;
h1.put(m,val);
}
else
{
h1.put(m,new Integer(1));
}
}
StringBuilder x=new StringBuilder();
for(int i=0;i<com.length();i++)
{
if(h1.containsKey(""+com.charAt(i)))
{
int count=(int)h1.get(""+com.charAt(i));
while(count!=0)
{x.append(""+com.charAt(i));count--;}
}
}
x.append(uncom);
System.out.println("Sort "+x);
}
}
Here is my version which is O(n) in time. Instead of unordered_map, I could have just used a char array of constant size. i.,e. char char_count[256] (and done ++char_count[ch - 'a'] ) assuming the input strings has all ASCII small characters.
string SortOrder(const string& input, const string& sort_order) {
unordered_map<char, int> char_count;
for (auto ch : input) {
++char_count[ch];
}
string res = "";
for (auto ch : sort_order) {
unordered_map<char, int>::iterator it = char_count.find(ch);
if (it != char_count.end()) {
string s(it->second, it->first);
res += s;
}
}
return res;
}
private static String sort(String target, String reference) {
final Map<Character, Integer> referencesMap = new HashMap<Character, Integer>();
for (int i = 0; i < reference.length(); i++) {
char key = reference.charAt(i);
if (!referencesMap.containsKey(key)) {
referencesMap.put(key, i);
}
}
List<Character> chars = new ArrayList<Character>(target.length());
for (int i = 0; i < target.length(); i++) {
chars.add(target.charAt(i));
}
Collections.sort(chars, new Comparator<Character>() {
#Override
public int compare(Character o1, Character o2) {
return referencesMap.get(o1).compareTo(referencesMap.get(o2));
}
});
StringBuilder sb = new StringBuilder();
for (Character c : chars) {
sb.append(c);
}
return sb.toString();
}
In C# I would just use the IComparer Interface and leave it to Array.Sort
void Main()
{
// we defin the IComparer class to define Sort Order
var sortOrder = new SortOrder("dfbcae");
var testOrder = "abcdeeabc".ToCharArray();
// sort the array using Array.Sort
Array.Sort(testOrder, sortOrder);
Console.WriteLine(testOrder.ToString());
}
public class SortOrder : IComparer
{
string sortOrder;
public SortOrder(string sortOrder)
{
this.sortOrder = sortOrder;
}
public int Compare(object obj1, object obj2)
{
var obj1Index = sortOrder.IndexOf((char)obj1);
var obj2Index = sortOrder.IndexOf((char)obj2);
if(obj1Index == -1 || obj2Index == -1)
{
throw new Exception("character not found");
}
if(obj1Index > obj2Index)
{
return 1;
}
else if (obj1Index == obj2Index)
{
return 0;
}
else
{
return -1;
}
}
}

function trying to put dot after n characters [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am trying to write a function, it has 2 parameters one is of string and another is of number datatype, my function has to place a dot after every N characters, where N is provided at run time (some number provided through number datatype). Can anybody help me out please?
This smells like homework, so let me suggest how to start, and then you can come back with how far you've gotten.
First, you need to be able to iterate over the string, or at least to jump forward N characters along its length. Can you think of a construct that allows you to either iterate each character until you've iterated N character, or that allows you to split the string into substrings N characters long?
What language?
In C#:
public string PutDots(string input, int n)
{
char[] c = input.ToCharArray();
StringBuilder output = new StringBuilder();
for (int i = 0; i < c.Length; i++)
{
output.Append(c[i]);
if (i % n == 0 && i > 0)
{
output.Append(".");
}
}
return output.ToString();
}
something like this maybe:
public string foo(string input, int count)
{
string result = "";
for(int i=0; i < input.length; i++)
{
result += input[i];
if(i % count == 0)
result += '.';
}
return result;
}
(Depending on the language you might want to use something else then string concatenation to build the resultingstring)
In C#:
static string InsertDots(string s, int n)
{
if(string.IsNullOrEmpty(s)) return s;
if(n <= 0 || n > s.Length) return s;
Regex re = new Regex(string.Format("(.{{{0}}})", n));
return re.Replace(s, "$1.");
}

Resources