cs151 Homework 7 Solution Fall 1999 Addition and concatenation -------------------------- Here is my version of the table boolean char int String boolean error error error stringCat char error int add int add stringCat int error int add int add stringCat String stringCat stringCat stringCat stringCat In other words, a String plus anything yields a String. Other than that, you can't add booleans to anything. The only thing in this table I don't like is the way characters get converted to integer. isPalindrome ------------ Here's first, last and middle: // first returns the first character of a string // first only works if s has at least one characters public static char first (String s) { return s.charAt (0); } // last returns the last character of a string // last only works if s has at least one characters public static char last (String s) { return s.charAt (s.length() - 1); } // middle returns a substring that includes all but the // first and last; only works if s has at least two characters public static String middle (String s) { return s.substring (1, s.length()-1); } Here are three versions of isPalindrome for the price of one! The first one is recursive: public static boolean isPalindrome (String s) { if (s.length() < 2) { return true; } else if (first(s) != last(s)) { return false; } else { return isPalindrome (middle (s)); } } Here is the first iterative one. It uses two index variables: i starts at the beginning of the word and goes forward; j starts at the end and goes backwards. We quit when they meet in the middle. At any step in the traversal, we compare the ith character to the jth character. If there are different, we know immediately that the word in not a palindrome. If we get all the way to the end without seeing a mismatch, it must be a palindrome. public static boolean isPalindrome2 (String s) { // an iterative version of isPalindrome int i = 0; int j = s.length()-1; while (i < j) { if (s.charAt(i) != s.charAt(j)) { return false; } i++; j--; } // if we get all the way through the loop and // never found a mismatched pair, it must be true! return true; } The next version is also iterative, but instead of using indices it works by whittling s down until we get to 0 or 1 characters. The iterative step is s = middle (s); Eventually that has to result in a very short string. public static boolean isPalindrome3 (String s) { // another iterative version of isPalindrome while (s.length() >= 2) { if (first(s) != last(s)) { return false; } else { s = middle (s); } } return true; } Names ----- public static boolean hasComma (String s) { int index = s.indexOf(','); return (index != -1); } public static String convertName (String s) { if (hasComma (s)) { return s; } s = s.toLowerCase (); int space = s.indexOf(' '); int len = s.length(); String first = s.substring (0, space); String last = s.substring (space+1, len); return last + ", " + first; } }