I have written code to find whether given string is anagram. for some permutations code is working fine but in some case it's failing. Any suggestion? - string

The above logic is working for some inputs but it get's fails while we apply some complex permutations of string. Please could anyone suggest any improvement in code and logic.
public class StringAnagram {
public static void main(String[] args) {
String s = "he_llo";
String s1 = "elloh";
boolean flag = false;
if (s.length() == s1.length()) {
for (int i = 0; i < s.length(); i++) {
for (int j = 0; j < s.length(); j++) {
if (s.charAt(i) == s1.charAt(j)) {
flag = true;
i++;
if(i==s.length())
break;
} else
flag = false;
}
}
} else
System.out.println("String length not match");
if(flag==true)
System.out.println("Anagram");
else
System.out.println("Not Anagram");
}
}

Related

Interleaving Strings LCS

Hi I was trying to solve the interleaving strings problem.Here is the detailed explanation of the problem. https://practice.geeksforgeeks.org/problems/interleaved-strings/1
I was trying using lcs but it was not passing leetcode cases. Here is my Code:-
(I am taking lcs from start and end)
class Solution {
public boolean isInterLeave(String a, String b, String c) {
StringBuffer s=new StringBuffer();
StringBuffer s1=new StringBuffer();
StringBuffer s2=new StringBuffer();
StringBuffer s4=new StringBuffer();
int m=a.length();
int n=c.length();
int q=b.length();
if(n!=m+q){
return false;
}
LinkedHashSet<Integer> res2= new LinkedHashSet<Integer>();
res2= lcs(a,c,m,n);
LinkedHashSet<Integer> res4= new LinkedHashSet<Integer>();
res4= lcs(b,c,q,n);
for(int i=0;i<n;i++){
if(res2.contains(i)==false){
s.append(c.charAt(i));
}
}
for(int i=0;i<n;i++){
if(res4.contains(i)==false){
s1.append(c.charAt(i));
}
}
LinkedHashSet<Integer> res5= new LinkedHashSet<Integer>();
res5= LCS(a,c,m,n);
for(int i=0;i<n;i++){
if(res5.contains(i)==false){
s2.append(c.charAt(i));
}
} LinkedHashSet<Integer> res6= new LinkedHashSet<Integer>();
res6= LCS(b,c,q,n);
for(int i=0;i<n;i++){
if(res6.contains(i)==false){
s4.append(c.charAt(i));
}
}
String z=s.toString();
String u=s1.toString();
String v=s2.toString();
String w=s4.toString();
if( (b.equals(z)==true || a.equals(u)==true) || ( b.equals(v)==true || a.equals(w)==true)){
return true;
}
else{
return false;
}
}
public static LinkedHashSet<Integer> lcs(String X, String Y, int m, int n)
{
int[][] L = new int[m+1][n+1];
// Following steps build L[m+1][n+1] in bottom up fashion. Note
// that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1]
for (int i=0; i<=m; i++)
{
for (int j=0; j<=n; j++)
{
if (i == 0 || j == 0)
L[i][j] = 0;
else if (X.charAt(i-1) == Y.charAt(j-1))
L[i][j] = L[i-1][j-1] + 1;
else
L[i][j] = Math.max(L[i-1][j], L[i][j-1]);
}
}
// Following code is used to print LCS
// Create a character array to store the lcs string
LinkedHashSet<Integer> linkedset =
new LinkedHashSet<Integer>();
// Start from the right-most-bottom-most corner and
// one by one store characters in lcs[]
int i=1;
int j=1;
while (i <= m && j <= n)
{
// If current character in X[] and Y are same, then
// current character is part of LCS
if (X.charAt(i-1) == Y.charAt(j-1))
{
// Put current character in result
linkedset.add(j-1);
// reduce values of i, j and index
i++;
j++;
}
// If not same, then find the larger of two and
// go in the direction of larger value
else if (L[i-1][j] > L[i][j-1])
i++;
else
j++;
}
return linkedset;
}
public static LinkedHashSet<Integer> LCS(String X, String Y, int m, int n)
{
int[][] L = new int[m+1][n+1];
// Following steps build L[m+1][n+1] in bottom up fashion. Note
// that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1]
for (int i=0; i<=m; i++)
{
for (int j=0; j<=n; j++)
{
if (i == 0 || j == 0)
L[i][j] = 0;
else if (X.charAt(i-1) == Y.charAt(j-1))
L[i][j] = L[i-1][j-1] + 1;
else
L[i][j] = Math.max(L[i-1][j], L[i][j-1]);
}
}
// Following code is used to print LCS
// Create a character array to store the lcs string
LinkedHashSet<Integer> linkedset =
new LinkedHashSet<Integer>();
// Start from the right-most-bottom-most corner and
// one by one store characters in lcs[]
int i = m;
int j = n;
while (i > 0 && j > 0)
{
// If current character in X[] and Y are same, then
// current character is part of LCS
if (X.charAt(i-1) == Y.charAt(j-1))
{
// Put current character in result
linkedset.add(j-1);
// reduce values of i, j and index
i--;
j--;
}
// If not same, then find the larger of two and
// go in the direction of larger value
else if (L[i-1][j] > L[i][j-1])
i--;
else
j--;
}
return linkedset;
}
}
Can anyone suggest an LCS approach to this problem?.My code is not passing the following test case
"cacabcbaccbbcbb" -String A
"acaaccaacbbbabbacc"-String B
"accacaabcbacaccacacbbbbcbabbbbacc"-String C
This will be the LCS+DP approach. Try it out:
class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
int m = s1.length(), n = s2.length();
if (n + m != s3.length()) return false;
if (s3.length() == 0) return true;
boolean[][] dp = new boolean[m+1][n+1];
dp[0][0] = true;
for (int i = 0; i <= m; i++) {
if (s1.substring(0, i).equals(s3.substring(0, i)))
dp[i][0] = true;
else
dp[i][0] = false;
}
for (int j = 0; j <= n; j++) {
if (s2.substring(0, j).equals(s3.substring(0, j)))
dp[0][j] = true;
else
dp[0][j] = false;
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
dp[i][j] = (dp[i-1][j] && s1.charAt(i-1) == s3.charAt(i+j-1))
|| (dp[i][j-1] && s2.charAt(j-1) == s3.charAt(i+j-1));
}
}
return dp[m][n];
}
}

groovy.lang.GroovyRuntimeException - Groovy error

I have been doing some test in Groovy. I have done this code and I and get this error
Caught: groovy.lang.GroovyRuntimeException: This script or class could not be run.
It should either:
have a main method,
be a JUnit test or extend GroovyTestCase,
implement the Runnable interface,
or be compatible with a registered script runner. Known runners:
none
class Prime {
public static def prime(int x){
boolean result = true;
int i, j, temp;
temp = 0;
if (x < 2){
result = false;
}else {
for(i = 2; i < x && j == 0; i++){
temp = x % i;
if(temp == 0){
result = false;
}
}
}
return result;
}
static void main() {
long time_start, time_end, time_exe;
int primes = 0;
int N = (int) Math.pow(8, 5);
time_start = System.currentTimeMillis();
def fichero = new File("salida2.out")
for (int i = 0; i <= N; i ++) {
if (prime(i) == true) {
String line = "" + i + " is prime.";
fichero.append(line);
}
}
time_end = System.currentTimeMillis();
time_exe = time_end - time_start;
println("Execution time: " + time_exe + "milliseconds");
println("Prime Numbers Found: " + primes);
}
}
The signature of your main method is incorrect (Need String... args).
Change it to:
public static void main(String... args) {

If I have given the word ssseeerabbcccdd then output should be like s3e3rab2c3d2 in c#

class Program
{
static void Main(string[] args)
{
Console.Write("Enter Word : ");
string word = Console.ReadLine();
for (var i = 0; i < word.Length; i++)
{
var check = true;
var count = 0;
for (var k = i - 1; k <= 0; k--)
{
if (word[k] == word[i]) check = false;
}
if (check)
{
for (var j = i; j<= word.Length; j++)
{
if (word[i] == word[j]) count++;
}
Console.WriteLine(word[i] + " Occurs at " + count + " places.");
}
}
Console.ReadLine();
}
}
I have tried this one but not working.
The problem is that check is set to false if the string contains two adjacent identical characters. So if (check) {...} won't be executed, if this is the case. Another problem is that you set k to string position -1 in the first iteration of for (var k = i - 1; k <= 0; k--). If i=0, then k will be -1. You also need only one inner loop.
Here is a possible solution, although slightly different than your's.
class Program
{
static void Main(string[] args)
{
Console.Write("Enter Word : ");
string word = Console.ReadLine();
int i = 0;
while (i < word.Length)
{
int count = 1;
for (int k = i+1; k < word.Length; k++)
if (word[i] == word[k])
count++;
if (count>1)
{
Console.WriteLine(word[i] + " Occurs at " + count + " places.");
}
i += count; // continue next char or after after repeated chars
}
Console.ReadLine();
}
}

Isomorphic Strings

Given two strings s and t, determine if they are isomorphic.
Two strings are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.
For example,
Given "egg", "add", return true.
Given "foo", "bar", return false.
Given "paper", "title", return true.
Note:
You may assume both s and t have the same length.
I have this solution but it is taking too much time.
Any good solution will be appreciated
public boolean isIsomorphic(String s, String t) {
String resString1="",resString2="";
HashMap<Character,Integer> hashmapS = new HashMap();
HashMap<Character,Integer> hashmapT = new HashMap();
boolean flag = false;
for(int i = 0;i<s.length();i++)
{
char chS = s.charAt(i);
char chT = t.charAt(i);
if(hashmapS.containsKey(chS))
{
resString1 = resString1 + hashmapS.get(chS);
}
else
{
resString1 = resString1 + i;
hashmapS.put(chS, i);
}
if(hashmapT.containsKey(chT))
{
resString2 = resString2 + hashmapT.get(chT);
}
else
{
resString2 = resString2 + i;
hashmapT.put(chT, i);
}
}
if(resString1.equals(resString2))
return true;
else
return false;
}
/* Time complexity = O(n)*/
public static boolean isIsomorphic (String s1 , String s2){
if (s1 == null || s2 == null){
throw new IllegalArgumentException();
}
if (s1.length() != s2.length()){
return false;
}
HashMap<Character, Character> map = new HashMap<>();
for (int i = 0 ; i < s1.length(); i++){
if (!map.containsKey(s1.charAt(i))){
if(map.containsValue(s2.charAt(i))){
return false;
}
else{
map.put(s1.charAt(i), s2.charAt(i));
}
}
else{
if( map.get(s1.charAt(i)) != s2.charAt(i)){
return false;
}
}
}
return true;
}
In your implementation, you will come to know of the answer only after processing both strings completely. While in many negative test cases, answer can be determined seeing the first violation itself.
For e.g. consider 1000 character long strings: "aa.." and "ba....". An elegant solution would have to return seeing the second character itself of two strings, as 'a' cannot map to both 'a' and 'b' here.
You may find this article helpful. It also points to a C++ based solution.
Important thing to note are:
Since number of possible elements will be max pow(2, sizeof(char)), it is helpful to keep your own hash with ASCII code being the key itself. It gives significant improvement over the use of generic hash tables.
In Case of C++, use of std::urordered_map is better than std::map and std::stl as the later one uses Balanced Binary Search trees only.
Here is another implementation but with less memory usage.
public class IsoMorphic {
private static boolean isIsomorphic(String s, String t) {
if (s.length() != t.length()) {
return false;
}
char characters1[] = new char[26];
char characters2[] = new char[26];
char array1[] = s.toCharArray();
char array2[] = t.toCharArray();
for (int i=0; i<array1.length; i++) {
char c1 = array1[i];
char c2 = array2[i];
char character1 = characters1[c1-'a'];
char character2 = characters2[c2-'a'];
if (character1 == '\0' && character2 == '\0') {
characters1[c1-'a'] = array2[i];
characters2[c2-'a'] = array1[i];
continue;
}
if (character1 == array2[i] && character2 == array1[i]) {
continue;
}
return false;
}
return true;
}
public static void main(String[] args) {
System.out.println(isIsomorphic("foo", "bar")); // false
System.out.println(isIsomorphic("bar", "foo")); // false
System.out.println(isIsomorphic("paper", "title")); // true
System.out.println(isIsomorphic("title", "paper")); // true
System.out.println(isIsomorphic("apple", "orange")); // false
System.out.println(isIsomorphic("aa", "ab")); // false
System.out.println(isIsomorphic("ab", "aa")); // false
}
}
http://www.programcreek.com/2014/05/leetcode-isomorphic-strings-java/
You should be figuring out the algorithm by yourself though.
Two words are called isomorphic if the letters in single word can be remapped to get the second word. Remapping a letter means supplanting all events of it with another letter while the requesting of the letters stays unaltered. No two letters may guide to the same letter, yet a letter may guide to itself.
public bool isomorphic(string str1, string str2)
{
if (str1.Length != str2.Length)
{
return false;
}
var str1Dictionary = new Dictionary<char, char>();
var str2Dictionary = new Dictionary<char, char>();
var length = str1.Length;
for (int i = 0; i < length; i++)
{
if (str1Dictionary.ContainsKey(str1[i]))
{
if (str1Dictionary[str1[i]] != str2[i])
{
return false;
}
}
else
{
str1Dictionary.Add(str1[i], str2[i]);
}
if (str2Dictionary.ContainsKey(str2[i]))
{
if (str2Dictionary[str2[i]] != str1[i])
{
return false;
}
}
else
{
str2Dictionary.Add(str2[i], str1[i]);
}
}
return true;
}
public class Isomorphic {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(isIsomorphic("foo", "bar"));
System.out.println(isIsomorphic("bar", "foo"));
System.out.println(isIsomorphic("foo", "bar"));
System.out.println(isIsomorphic("bar", "foo"));
System.out.println(isIsomorphic("turtle", "tletur"));
System.out.println(isIsomorphic("tletur", "turtle"));
System.out.println(isIsomorphic("turtle", "tletur"));
System.out.println(isIsomorphic("tletur", "turtle"));
}
public static boolean isIsomorphic(String s1,String s2) {
if(s1.length()!=s2.length()) {
return false;
}
if(s1.length()==1) {
return true;
}
int c1;
int c2;
for(int i=0;i<s1.length()-1;i++) {
c1=s1.charAt(i);
c2=s1.charAt(i+1);
if(c1==c2) {
c1=s2.charAt(i);
c2=s2.charAt(i+1);
if(c1==c2) {
continue;
}else {
return false;
}
}else if(c1!=c2) {
c1=s2.charAt(i);
c2=s2.charAt(i+1);
if(c1!=c2) {
continue;
}else {
return false;
}
}
}
return true;
}
}
Comments are welcome !!
public bool IsIsomorphic(string s, string t)
{
if (s == null || s.Length <= 1) return true;
Dictionary<char, char> map = new Dictionary<char, char>();
for (int i = 0; i < s.Length; i++)
{
char a = s[i];
char b = t[i];
if (map.ContainsKey(a))
{
if (map[a]==b)
continue;
else
return false;
}
else
{
if (!map.ContainsValue(b))
map.Add(a, b);
else return false;
}
}
return true;
}
Here is my implementation...
private static boolean isIsmorphic(String string1, String string2) {
if(string1==null) return false;
if(string2==null) return false;
if(string1.length()!=string2.length())return false;
HashMap<Character,Character> map=new HashMap<>();
for(int i=0;i<string1.length();i++){
char c1=string1.charAt(i);
char c2=string2.charAt(i);
if(map.get(c1)!=null && !map.get(c1).equals(c2)){
return false;
}
map.put(c1, c2);
}
return true;
}
public class Solution {
public boolean isIsomorphic(String s, String t) {
int[] m = new int[512];
for (int i = 0; i < s.length(); i++) {
if (m[s.charAt(i)] != m[t.charAt(i)+256]) return false;
m[s.charAt(i)] = m[t.charAt(i)+256] = i+1;
}
return true;
}
}
I didn't find an answer without using Maps here, so posting my implementation which don't use additional memory.
Actually using HashMap to check if words are isomorphic is very slow on short words. On my computer using the implementation is faster up to 20 symbols in test words.
static boolean isIsomorphic(String s1, String s2) {
if (s1 == null || s2 == null) return false;
final int n = s1.length();
if (n != s2.length()) return false;
for (int i = 0; i < n; i++) {
final char c1 = s1.charAt(i);
final char c2 = s2.charAt(i);
for (int j = i + 1; j < n; j++) {
if (s1.charAt(j) == c1 && s2.charAt(j) != c2) return false;
if (s2.charAt(j) == c2 && s1.charAt(j) != c1) return false;
}
}
return true;
}
Java implementation using HashMap and HashSet. O(N) = n, O(S) = c, where c is the size of the character set.
boolean isIsomorphic(String s, String t){
HashMap<Character, Character> map = new HashMap<>();
HashSet<Character> set = new HashSet<>();
if(s.length() != t.length())
return false;
for (int i = 0; i < s.length(); i++) {
if(map.containsKey(s.charAt(i))){
if(map.get(s.charAt(i)) != t.charAt(i))
return false;
} else if(set.contains(t.charAt(i))) {
return false;
} else {
map.put(s.charAt(i), t.charAt(i));
set.add(t.charAt(i));
}
}
return true;
}
There are many different ways on how to do it. Below I provided three different ways by using a dictionary, set, and string.translate.
Here I provided three different ways how to solve Isomorphic String solution in Python.
This is the best solution I think
public boolean areIsomorphic(String s1,String s2)
{
if(s1.length()!=s2.length())
return false;
int count1[] = new int[256];
int count2[] = new int[256];
for(int i=0;i<s1.length();i++)
{
if(count1[s1.charAt(i)]!=count2[s2.charAt(i)])
return false;
else
{
count1[s1.charAt(i)]++;
count2[s2.charAt(i)]++;
}
}
return true;
}
C# soluation:
public bool isIsomorphic(String string1, String string2)
{
if (string1 == null || string2 == null)
return false;
if (string1.Length != string2.Length)
return false;
var data = new Dictionary<char, char>();
for (int i = 0; i < string1.Length; i++)
{
if (!data.ContainsKey(string1[i]))
{
if (data.ContainsValue(string2[i]))
return false;
else
data.Add(string1[i], string2[i]);
}
else
{
if (data[string1[i]] != string2[i])
return false;
}
}
return true;
}

Substring algorithm

Can someone explain to me how to solve the substring problem iteratively?
The problem: given two strings S=S1S2S3…Sn and T=T1T2T3…Tm, with m is less than or equal to n, determine if T is a substring of S.
Here's a list of string searching algorithms
Depending on your needs, a different algorithm may be a better fit, but Boyer-Moore is a popular choice.
A naive algorithm would be to test at each position 0 < i ≤ n-m of S if Si+1Si+2…Si+m=T1T2…Tm. For n=7 and m=5:
i=0: S1S2S3S4S5S6S7
| | | | |
T1T2T3T4T5
i=1: S1S2S3S4S5S6S7
| | | | |
T1T2T3T4T5
i=2: S1S2S3S4S5S6S7
| | | | |
T1T2T3T4T5
The algorithm in pseudo-code:
// we just need to test if n ≤ m
IF n > m:
// for each offset on that T can start to be substring of S
FOR i FROM 0 TO n-m:
// compare every character of T with the corresponding character in S plus the offset
FOR j FROM 1 TO m:
// if characters are equal
IF S[i+j] == T[j]:
// if we’re at the end of T, T is a substring of S
IF j == m:
RETURN true;
ENDIF;
ELSE:
BREAK;
ENDIF;
ENDFOR;
ENDFOR;
ENDIF;
RETURN false;
Not sure what language you're working in, but here's an example in C#. It's a roughly n2 algorithm, but it will get the job done.
bool IsSubstring (string s, string t)
{
for (int i = 0; i <= (s.Length - t.Length); i++)
{
bool found = true;
for (int j = 0; found && j < t.Length; j++)
{
if (s[i + j] != t[j])
found = false;
}
if (found)
return true;
}
return false;
}
if (T == string.Empty) return true;
for (int i = 0; i <= S.Length - T.Length; i++) {
for (int j = 0; j < T.Length; j++) {
if (S[i + j] == T[j]) {
if (j == (T.Length - 1)) return true;
}
else break;
}
}
return false;
It would go something like this:
m==0? return true
cs=0
ct=0
loop
cs>n-m? break
char at cs+ct in S==char at ct in T?
yes:
ct=ct+1
ct==m? return true
no:
ct=0
cs=cs+1
end loop
return false
This may be redundant with the above list of substring algorithms, but I was always amused by KMP (http://en.wikipedia.org/wiki/Knuth–Morris–Pratt_algorithm)
// runs in best case O(n) where no match, worst case O(n2) where strings match
var s = "hippopotumus"
var t = "tum"
for(var i=0;i<s.length;i++)
if(s[i]==t[0])
for(var ii=i,iii=0; iii<t.length && i<s.length; ii++, iii++){
if(s[ii]!=t[iii]) break
else if (iii==t.length-1) console.log("yay found it at index: "+i)
}
Here is my PHP variation that includes a check to make sure the Needle does not exceed the Haystacks length during the search.
<?php
function substring($haystack,$needle) {
if("" == $needle) { return true; }
echo "Haystack:\n$haystack\n";
echo "Needle:\n$needle\n";
for($i=0,$len=strlen($haystack);$i<$len;$i++){
if($needle[0] == $haystack[$i]) {
$found = true;
for($j=0,$slen=strlen($needle);$j<$slen;$j++) {
if($j >= $len) { return false; }
if($needle[$j] != $haystack[$i+$j]) {
$found = false;
continue;
}
}
if($found) {
echo " . . . . . . SUCCESS!!!! startPos: $i\n";
return true;
}
}
}
echo " . . . . . . FAILURE!\n" ;
return false;
}
assert(substring("haystack","hay"));
assert(!substring("ack","hoy"));
assert(substring("hayhayhay","hayhay"));
assert(substring("mucho22","22"));
assert(!substring("str","string"));
?>
Left in some echo's. Remove if they offend you!
Is a O(n*m) algorithm, where n and m are the size of each string.
In C# it would be something similar to:
public static bool IsSubtring(char[] strBigger, char[] strSmall)
{
int startBigger = 0;
while (startBigger <= strBigger.Length - strSmall.Length)
{
int i = startBigger, j = 0;
while (j < strSmall.Length && strSmall[j] == strBigger[i])
{
i++;
j++;
}
if (j == strSmall.Length)
return true;
startBigger++;
}
return false;
}
I know I'm late to the game but here is my version of it (in C#):
bool isSubString(string subString, string supraString)
{
for (int x = 0; x <= supraString.Length; x++)
{
int counter = 0;
if (subString[0] == supraString[x]) //find initial match
{
for (int y = 0; y <= subString.Length; y++)
{
if (subString[y] == supraString[y+x])
{
counter++;
if (counter == subString.Length)
{
return true;
}
}
}
}
}
return false;
}
Though its pretty old post, I am trying to answer it. Kindly correct me if anything is wrong,
package com.amaze.substring;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CheckSubstring {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter the main string");
String mainStr = br.readLine();
System.out.println("Enter the substring that has to be searched");
String subStr = br.readLine();
char[] mainArr = new char[mainStr.length()];
mainArr = mainStr.toCharArray();
char[] subArr = new char[subStr.length()];
subArr = subStr.toCharArray();
boolean tracing = false;
//System.out.println("Length of substring is "+subArr.length);
int j = 0;
for(int i=0; i<mainStr.length();i++){
if(!tracing){
if(mainArr[i] == subArr[j]){
tracing = true;
j++;
}
} else {
if (mainArr[i] == subArr[j]){
//System.out.println(mainArr[i]);
//System.out.println(subArr[j]);
j++;
System.out.println("Value of j is "+j);
if((j == subArr.length)){
System.out.println("SubString found");
return;
}
} else {
j=0;
tracing = false;
}
}
}
System.out.println("Substring not found");
}
}

Resources