class Solution {
public static void main(String[] args) {
System.out.println("Should be (fl). ="+new Solution().longestCommonPrefix(new String[]{"flower","flow","flight"}));
System.out.println("Should be (""). ="+new Solution().longestCommonPrefix(new String[]{"box","wow","cat"}));
}
public String longestCommonPrefix(String[] strs) {
String firstString = strs[0];
String commonPrefix="";
boolean common=true;
for(int j=0; j
Wednesday, February 9, 2022
Longest Common Prefix
function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Roman to decimal conversion
class Solution {
public static void main(String[] args) {
System.out.println("Should be (3). ="+new Solution().romanToInt("III"));
System.out.println("Should be (58). ="+new Solution().romanToInt("LVIII"));
System.out.println("Should be (1994). ="+new Solution().romanToInt("MCMXCIV"));
}
public int romanToInt(String s) {
Map romanValues = new HashMap();
romanValues.put("I", "1");
romanValues.put("V", "5");
romanValues.put("X", "10");
romanValues.put("L", "50");
romanValues.put("C", "100");
romanValues.put("D", "500");
romanValues.put("M", "1000");
String romanNum = s;
int intValue=0;
int prevValue=0;
for(int i=0; i< s.length(); i++){
String firstChar = romanNum.substring(0,1);
if(firstChar==null)
continue;
System.out.println("firstChar= "+firstChar);
int romanIntValue= Integer.valueOf((String)romanValues.get(firstChar));
System.out.println("romanIntValue= "+romanIntValue);
if(romanIntValue > prevValue){
romanIntValue -=prevValue;
intValue -=prevValue;
}
prevValue=romanIntValue;
intValue +=romanIntValue;
System.out.println("intValue= "+intValue);
romanNum = romanNum.substring(1, romanNum.length());
System.out.println("romanNum= "+romanNum);
}
return intValue;
}
}
Polindrome
Given an integer x
, return true
if x
is palindrome integer.
An integer is a palindrome when it reads the same backward as forward.
- For example,
121
is a palindrome while123
is not.
class Polindrome {public boolean isPalindrome(int x) {int given =x;int reverse=0;while(given >0){reverse = 10*reverse +given%10;given = given/10;}if(reverse == x)return true;return false;}}
This one only goes through half the elements
class Palindrome {public boolean isPalindrome(int x) {
// negative numbers are not a palindrome
//any number with zero in units. but not Zero by itself
if(x<0 || (x % 10 == 0 && x != 0) )return false;int numDigits = String.valueOf(x).length();int half = numDigits/2;int rev=0;int given = x;for(int i=0;i<half;i++){rev = 10*rev+given%10;given=given/10;}if(numDigits%2 != 0)given = given/10;if(rev==given)return true;return false;}}
Subscribe to:
Posts (Atom)