public class Solution {
public static void main(String[] args) {
System.out.println(romanToInt("DCXXI"));
}
public static int romanToInt(String s) {
int ln = s.length()-1;
int ans = 0;
int i=0;
while (i <=ln){
if (s.charAt(i) == 'M'){
ans += 1000;
}else if (s.charAt(i) == 'D'){
ans += 500;
}else if (s.charAt(i) == 'C' && s.charAt(i+1)=='D'){
ans += 400;
i=i+1;
}else if (s.charAt(i) == 'C' && s.charAt(i+1)=='M'){
ans += 900;
i=i+1;
}else if (s.charAt(i) == 'C'){
ans += 100;
}else if (s.charAt(i) == 'L'){
ans += 50;
}else if (s.charAt(i) == 'X' && s.charAt(i+1)=='L'){
ans += 40;
i=i+1;
}else if (s.charAt(i) == 'X' && s.charAt(i+1)=='C'){
ans += 90;
i=i+1;
}else if (s.charAt(i) == 'X'){
ans += 10;
}else if (s.charAt(i) == 'V'){
ans += 5;
}else if (s.charAt(i)=='I' && s.charAt(i+1)=='V'){
ans += 4;
i=i+1;
}else if (s.charAt(i)=='I' && s.charAt(i+1)=='X'){
ans += 9;
i=i+1;
}else if (s.charAt(i)=='I'){
ans += 1;
}
i++;
System.out.printf("Current sum is: %s and current pointer i is: %s \n",ans, i);
}
return ans;
}
}
I keep getting error message
java.lang.StringIndexOutOfBoundsException: String index out of range:
5
But I couldn't find where I did it wrong. Can someone help me?
Output:
This is D
Current sum is: 500 and current pointer i is: 1
This is C
Current sum is: 600 and current pointer i is: 2
This is X
Current sum is: 610 and current pointer i is: 3
This is X
Current sum is: 620 and current pointer i is: 4
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
at java.lang.String.charAt(Unknown Source)
at Solution.romanToInt(Solution.java:65)
at Solution.main(Solution.java:9)
You set
int ln = s.length()-1;
and use
while (i <=ln){....}
then get
s.charAt(i+1)
so it is possibly i+1 >= s.length();
then s.charAt(i+1) will throw Exception
The problem here is that when you are at the last character of the string provided, you are testing, sometimes, string.charAt(i+1) that causes your IndexOutofBound exceptions.
These two "else if" cases caused the exception:
}else if (s.charAt(i+1)=='I' && s.charAt(i+1)=='V'){
....
}else if (s.charAt(i+1)=='I' && s.charAt(i+1)=='X'){
....
Related
I'm trying to make a simple function in dart to test on which should remove all vowels from an input string but its seems my code never changes the from the original input. Could anyone help me with this? thanks
String removeVowel( str) {
var toReturn = "";
for (var i = 0; i < str.length; i++) {
var temp = str.substring(i,i+1);
if (temp != 'a' || temp != 'e' || temp != 'i' || temp != 'o' || temp!= 'u')
{
toReturn = toReturn + temp;
}
}
return toReturn;
}
and what my tests shows:
00:02 +0 -1: dog --> dg [E]
Expected: 'dg'
Actual: 'dog'
Which: is different.
Expected: dg
Actual: dog
^
Differ at offset 1
Good first try but there is a much easier way of doing this.
replaceAll should do the trick
String removeVolwels(String s){
return s.replaceAll(RegExp('[aeiou]'),'');
}
https://api.flutter.dev/flutter/dart-core/String/replaceAll.html
To make your code work you should change the || to &&
String removeVowel( str) {
var toReturn = "";
for (var i = 0; i < str.length; i++) {
var temp = str.substring(i,i+1);
if (temp != 'a' && temp != 'e' && temp != 'i' && temp != 'o' && temp!= 'u')
{
toReturn = toReturn + temp;
}
}
return toReturn;
}
Here is the problem link: https://leetcode.com/problems/roman-to-integer/
I kept having problem on comparison s.charAt() and a char of Roman.
I am very new to JAVA. Isn't if(s.charAt(i) == 'I') supposed to work?
I saw other solutions of this problem, but the solutions tend to make a char and put the char of string in that char.
Could you please explain why my comparison is not working?
I really appreciate your answer in advance.
class Solution {
public int romanToInt(String s) {
int i = 0;
int sum = 0;
for(i=0;i<s.length();i++)
{
if(s.charAt(i) == 'I')
{
if(s.charAt(i+1) == 'X') //4
{
i++;
sum += 4;
}
else if(s.charAt(i+1) == 'V') //9
{
i++;
sum += 9;
}
else
{
sum += 1;
}
}
else if(s.charAt(i) == 'V')
{
sum += 10;
}
else if(s.charAt(i) == 'X')
{
if(s.charAt(i+1) == 'L') //40
{
i++;
sum += 40;
}
else if(s.charAt(i+1) == 'C') //90
{
i++;
sum += 90;
}
else
{
sum += 10;
}
}
else if(s.charAt(i) == 'L')
{
sum += 50;
}
else if(s.charAt(i) == 'C')
{
if(s.charAt(i+1) == 'D') //400
{
i++;
sum += 400;
}
else if(s.charAt(i+1) == 'M') //900
{
i++;
sum += 900;
}
else
{
sum+=100;
}
}
else if(s.charAt(i) == 'D')
{
sum += 500;
}
else if(s.charAt(i) == 'M')
{
sum += 1000;
}
}
return sum;
}
}
I used Java for this:
public int romanToInt(String s) {
HashMap<Character, Integer> dict = new HashMap<Character, Integer>();
{
dict.put('I', 1);
dict.put('V', 5);
dict.put('X', 10);
dict.put('L', 50);
dict.put('C', 100);
dict.put('D', 500);
dict.put('M', 1000);
}
int temp = 0;
for(int i=0; i<s.length(); i++){
char c= s.charAt(i);
temp += dict.get(c);
char d= '.';
if((i+1)<s.length() && d!=c){
d = s.charAt(i+1);
if((c=='I' && (d=='V' || d=='X')) ||
(c=='X' && (d=='L' || d=='C')) ||
(c=='C' && (d=='D' || d=='M')))
{
temp += dict.get(d)-2*dict.get(c);
i++;
}
}
}
return temp;
}
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];
}
}
I'm trying to compile this program in c (for a cs50 online class), and keep getting the following error:
fifteen.c:233:1: error: control may reach end of non-void function [-Werror,-Wreturn-type]
}
I'm not asking about the logic of my code, but more looking for the syntax error that I've been missing for the last hour. Code is below. Thanks!
bool move(int tile)
{
for (int i = 0; i < d - 1; i++){
for (int j= 0; j < d - 1; j++){
if (tile == board[i][j]){
if (board[i+1][j] == tile){
board[i+1][j] = 0;
board[i+1][j] = tile;
return true;
}
else if (board [i-1][j] == 0){
board[i-1][j] = tile;
board [i-1][j] = 0;
return true;
}
else if (board [i][j+1] == 0){
board[i][j+1] = tile;
board [i][j+1] = 0;
return true;
}
else if (board [i][j-1] == 0){
board[i][j-1] = tile;
board [i][j-1] = 0;
return true;
}
}
return false;
}
}
}
This error is saying that your method can reach the end without returning a value. This is happening in this case because your brackets are out of place.
Try the following:
bool move(int tile) {
for (int i = 0; i < d - 1; i++) {
for (int j = 0; j < d - 1; j++) {
if (tile == board[i][j]) {
if (board[i+1][j] == tile) {
board[i+1][j] = 0;
board[i+1][j] = tile;
return true;
}
else if (board [i-1][j] == 0){
board[i-1][j] = tile;
board [i-1][j] = 0;
return true;
}
else if (board [i][j+1] == 0){
board[i][j+1] = tile;
board [i][j+1] = 0;
return true;
}
}
else if (board [i][j-1] == 0){
board[i][j-1] = tile;
board [i][j-1] = 0;
return true;
}
}
}
return false;
}
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");
}
}