Swap Two Coderbyte Solution

0

Have the function SwapII(str) take the str parameter and swap the case of each character. Then, if a letter is between two numbers (without separation), switch the places of the two numbers.

For example: if str is "6Hello4 -8World, 7 yes3" the output should be 4hELLO6 -8wORLD, 7 YES3.

Swap Two Coderbyte Java


import java.util.Scanner;


public class SwapTwo {
final String UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
final String LOWER = UPPER.toLowerCase();
final String NUMBERS = "0123456789";

String SwapII(String str) {
StringBuilder result = new StringBuilder("");

int prevNumIndex = -1;
boolean allCharsAfterPrevNum = false;
for (char c : str.toCharArray()) {
int index = UPPER.indexOf(c);
if (index != -1) {
result.append(LOWER.charAt(index));
} else {
index = LOWER.indexOf(c);

if (index != -1) {
result.append(UPPER.charAt(index));
} else {
index = NUMBERS.indexOf(c);
if (index != -1) {
if (prevNumIndex != -1 && allCharsAfterPrevNum) {
char prevNum = result.charAt(prevNumIndex);
result.setCharAt(prevNumIndex, c);
result.append(prevNum);
} else {
result.append(c);
}
allCharsAfterPrevNum = true;
prevNumIndex = result.length() - 1;
} else {
allCharsAfterPrevNum = false;
result.append(c);
}

}
}
}

return result.toString();
}

public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
SwapTwo c = new SwapTwo();
System.out.print(c.SwapII(s.nextLine()));
}
}


Swap ii coderbyte solution

def change(s,indx1,indx2):
res=''
for i in range(len(s)):
if i== indx1:
res += s[indx2]
elif i== indx2:
res += s[indx1]
else:
res += s[i]
return res

def tran(s):
arr=[]
for i in range(len(s)):
if s[i] in '0123456789':
arr.append(i)
if len(arr)<2:
return s
for i in range(arr[0]+1, arr[1]):
if (s[i]>="a" and s[i]<="z") or (s[i]>="A" and s[i]<="Z"):
return change(s, arr[0], arr[1])
else:
return s
def SwapII(str):
res=''
for i in str:
if i>="a" and i<="z":
res += i.upper()
elif i>="A" and i<="Z":
res += i.lower()
else:
res +=i
res1=res.split()
lst=[]
for i in range(len(res1)):
lst.append(tran(res1[i]))
return ' '.join(lst)
# keep this function call here
# to see how to enter arguments in Python scroll down
print SwapII(raw_input())

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment (0)
Our website uses cookies to enhance your experience. Learn More
Accept !